对于结构体,我是否必须在 C# 中显式调用构造函数?
问题是关于结构的。当我声明一个结构类型变量/对象(不知道哪一个更适合)或一个数组或结构列表时,我是否必须像对象一样显式调用构造函数,或者只是像变量一样声明就足够了?
The question is about the structs. When I declare a struct type variable/object (don't know which one suits better) or an array or list of structs, do I have to call the constructor explicitly like objects or just declaring will suffice like variables?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C# 中的结构体可以通过调用或不调用构造函数来创建。在没有调用构造函数的情况下,struct 将被初始化为默认值(基本上归零),并且无法使用
struct
直到它的所有字段都被初始化。从文档中:
下面是一些示例:
结构数组与单个结构变量不同。当您声明结构类型的数组时,您正在声明一个引用变量 - 因此,您必须使用 new 运算符分配它:
如果您的结构具有构造函数,您还可以选择使用数组初始化语法:
你可以变得比这更复杂。如果您的 struct 具有原始类型的隐式转换运算符,您可以像这样初始化它:
Structs in C# can be created with or without invoking a constructor. In the case when no constructor is invoked, the members of the struct will be initialized to default values (essentially zeroed out), and the
struct
cannot be used until all of its fields are initialized.From the documentation:
Below are some examples:
Arrays of structs are different than a single struct variable. When you declare an array of a struct type you are declaring a reference variable - as such, you must allocate it using the
new
operator:You can also choose to use array initialization syntax if your struct has a constructor:
You can get more sophisticated than this. If your
struct
has an implicit conversion operator from a primitive type, you can initialize it like so:Struct 是 C# 中的一种
值类型
,因此它使用堆栈内存而不是堆。您可以按照常规方式声明结构体变量,例如
int a = 90;
,int是C#中的结构体类型。
如果您使用 new 运算符,则会调用相应的构造函数。
Struct is a
Value Type
in C#, so it uses Stack memory rather than Heap.You can declare a struct variable in the regular way e.g
int a = 90;
,int is a struct type in c#.
If you use
new
operator then the corresponding constructor will be invoked.