当将 ValueType 声明为类的一部分时,它是否会被装箱?

发布于 2024-10-03 00:53:53 字数 179 浏览 1 评论 0原文

考虑到这个类:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

樱娆 2024-10-10 00:53:53

不,不是每次使用时都装箱。仅当您将值类型强制转换为引用类型时才会发生装箱 - 它实际上与分配该值的实际内存的位置(或者即使分配了任何内存)无关。

就您而言,您对 MyField 的操作方式将决定它是否被装箱,而不是 Foo 的处理方式。

  //No Boxing
  var f = new Foo();
  f.MyField = 5;
  int val = f.MyField;


  //Boxing
  var f = new Foo();
  f.MyFIeld = 5;
  object val = f.MyField;

请注意,在第二个示例中 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.

  //No Boxing
  var f = new Foo();
  f.MyField = 5;
  int val = f.MyField;


  //Boxing
  var f = new Foo();
  f.MyFIeld = 5;
  object val = f.MyField;

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)

宣告ˉ结束 2024-10-10 00:53:53

不,值类型没有装箱。

仅当您像对象一样使用值类型时才会发生装箱,例如将 int 存储在 object 数组中时。也就是说:

object[] a = new object[10];
int x = 1;
a[0] = x;

在这种情况下,值类型被装箱。

但是作为字段存储在类中的值类型不会被装箱。

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 of object. That is:

object[] a = new object[10];
int x = 1;
a[0] = x;

In that case, the value type is boxed.

But a value type stored as a field inside a class is not boxed.

烂柯人 2024-10-10 00:53:53

不,仅当值类型被视为 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)

夏雨凉 2024-10-10 00:53:53

值类型仅在分配给引用类型变量(例如object)时才会被装箱。如果您从未将 MyField 分配给除 int 或可以转换为的其他结构(例如 double)之外的任何内容,则它永远不会被装箱。

Value types only get boxed when they're assigned to a reference type variable (e.g. object). If you never assign MyField to anything other than an int or another struct to which it can be cast (e.g. double), it won't ever be boxed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文