当将 ValueType 声明为类的一部分时,它是否会被装箱?
考虑到这个类:
public class Foo
{
public Int32 MyField;
}
我猜“MyField”成员不在线程堆栈上,因为它可以被多个线程访问,所以它必须肯定在托管堆中,但这是否意味着每次使用它时都会将其装箱和拆箱?
提前致谢
Considering this class:
public class Foo
{
public Int32 MyField;
}
I guess the "MyField" member is not on the thread stack because as it could be accessed by several threads, it has to be definitely in the managed heap, but does it means it is boxed and unboxed everytime it is used?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,不是每次使用时都装箱。仅当您将值类型强制转换为引用类型时才会发生装箱 - 它实际上与分配该值的实际内存的位置(或者即使分配了任何内存)无关。
就您而言,您对 MyField 的操作方式将决定它是否被装箱,而不是 Foo 的处理方式。
请注意,在第二个示例中
val
现在包含对装箱 int 的引用。MyField
仍然(并将始终保持)一个未装箱的 int,无需拆箱即可访问(感谢您指出所需的说明,路加H)No, it is not boxed every time it is used. Boxing only occurs when you are coercing a value type into a reference type - it really has nothing to do with where the actual memory for the value was allocated (or even if any memory was allocated).
In your case, it's how you act on MyField that will determine if it's boxed, not how Foo is treated.
Note that in the second example
val
now contains a reference to a boxed int.MyField
is still (and will always remain) an unboxed int and can be accessed without unboxing (thanks for pointing out the needed clarification, LukeH)不,值类型没有装箱。
仅当您像对象一样使用值类型时才会发生装箱,例如将
int
存储在object
数组中时。也就是说:在这种情况下,值类型被装箱。
但是作为字段存储在类中的值类型不会被装箱。
No, the value type is not boxed.
Boxing only occurs when you use a value type as though it is an object, for example when storing an
int
in an array ofobject
. That is:In that case, the value type is boxed.
But a value type stored as a field inside a class is not boxed.
不,仅当值类型被视为 System.Object 时才会发生装箱(通常通过隐式转换,即将其作为方法参数传递)
No, boxing only occurs when a value type is treated as a System.Object (usually by implicit casting, i.e. passing it as a method parameter)
值类型仅在分配给引用类型变量(例如
object
)时才会被装箱。如果您从未将MyField
分配给除 int 或可以转换为的其他结构(例如double
)之外的任何内容,则它永远不会被装箱。Value types only get boxed when they're assigned to a reference type variable (e.g.
object
). If you never assignMyField
to anything other than an int or another struct to which it can be cast (e.g.double
), it won't ever be boxed.