为什么这个 ByteArray 实验会导致 AIR 崩溃
我正在将数据写入一个新的 ByteArray 并将其存储到 LocalStore
var ba:ByteArray = new ByteArray;
ba.writeObject(theobject);
EncryptedLocalStore.setItem(MY_VAL_STORE, ba); //bytes in local store
作为一个实验,我试图将前两行变成一行,所以我使用这种语法(我基本上将新的 ByteArray 放在括号中,然后立即使用它)。
var ba:ByteArray = (new ByteArray).writeObject(theobject) as ByteArray;
EncryptedLocalStore.setItem(MY_VAL_STORE, ba); //bytes in local store
但这导致我的 AIR 应用程序在运行时崩溃。如果我回到 2 行,效果很好。我意识到这没什么大不了的,但我很好奇为什么这种创造性的语法不起作用。有什么想法吗?
注意:在 1 行版本中,如果我不添加 as ByteArray
,它会抱怨我正在尝试将 void 类型与 ByteArray 一起使用。
I'm writing data into a new ByteArray and storing it into LocalStore
var ba:ByteArray = new ByteArray;
ba.writeObject(theobject);
EncryptedLocalStore.setItem(MY_VAL_STORE, ba); //bytes in local store
As an experiment, I'm trying to turn the 1st 2 lines into a single line, so I'm using this syntax (I basically put the new ByteArray in brackets and use it right away).
var ba:ByteArray = (new ByteArray).writeObject(theobject) as ByteArray;
EncryptedLocalStore.setItem(MY_VAL_STORE, ba); //bytes in local store
But this is making my AIR app crash at runtime. If I go back to the 2 lines, it works fine. I realize this isn't such a big deal, but I'm curious why this creative syntax isn't working. Any ideas?
note: in the 1-line version, if I don't add as ByteArray
, it complains that I'm trying to use type void with ByteArray.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您自己已经回答了您的问题:
在声明中,您将
writeObject()
的结果分配给 ByteArray 变量,而不是由new ByteArray()
创建的实例。由于结果类型为void
,因此该赋值是非法的,并会导致编译器抛出错误。然后,您将void
手动转换为 ByteArray,这显然足以欺骗编译器,但不能防止运行时出现类型转换错误。简而言之:只有当新实例上调用的方法返回
this
时,这种类型的赋值才有效。顺便说一下,一种使代码更具可读性的有用方法,也称为方法链接的概念。You've answered your question yourself:
In your declaration, you assign the result of
writeObject()
to your ByteArray variable, not the instance created bynew ByteArray()
. Since the result type isvoid
, this assignment is illegal and causes the compiler to throw an error. You've then added a manual cast ofvoid
to ByteArray, which obviously is enough to fool the compiler, but does not prevent a type cast error at runtime.In short: This type of assignment works only if the methods called on the new instance return
this
. A useful means to make code more readable, by the way, also known as the concept of Method Chaining.查看 writeObject 调用 我猜您的代码不起作用,因为该方法的返回值为
void
并且您尝试将其转换为ByteArray
。Looking at the documentation for the writeObject call I guess that your code isn't working because the return value of the method is
void
and you try to cast it to anByteArray
.