在堆上构造? [英] Struct on the heap?

查看:50
本文介绍了在堆上构造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个:

class SimpleDateStructureDemo
{

  struct Date
  {
    public int year;
    public int month;
    public int day;
  }

  static void Main()
  {
    ...
  }

}

然后我看到一个例子,说对象是在堆上分配的:

And then I see an example, saying that the object is allocated on the heap:

Date dateMoonWalk = new Date();

我认为类是引用类型,结构是值类型.最后,你可以通过使用new在堆上创建一个struct类型的对象,对吗?

I thought that classes are ref type, and structs are value type. In the end, you CAN create a struct type object on the heap by just using new, right?

推荐答案

你可以只使用 new 在堆上创建一个结构类型的对象,对吗?

you CAN create a struct type object on the heap by just using new, right?

不,如果你在 Main 内部这样做,一般来说,它不会在堆上分配.不过,您可以通过多种方式在堆上分配结构体,包括将其用作类中的字段、在闭包中使用它等.

No, if you do that inside of Main, in general, it won't get allocated on the heap. You can allocate a struct on the heap in many ways, though, including using it as a field in a class, using it in a closure, etc.

new Date 语法只是将结构初始化为其默认(清零)值,但实际上并没有改变它的分配方式或位置.

The new Date syntax just initializes the struct to it's default (zeroed out) value, but doesn't actually change how or where it's allocated.

这篇关于在堆上构造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆