问题在于结构。当我声明一个struct类型的变量/对象(不知道哪个更适合)或者一个数组或结构列表时,我是否必须像对象一样明确地调用构造函数,或者只是声明就像变量一样?
答案 0 :(得分:13)
可以在调用或不调用构造函数的情况下创建C#中的结构。如果没有调用构造函数,struct的成员将初始化为默认值(基本上为零) out),struct
在初始化所有字段之前不能使用。
来自文档:
使用时创建struct对象 新的运算符,它被创建和 调用适当的构造函数。 与类不同,结构可以是 实例化而不使用新的 运营商。如果你不使用新的, 字段将保持未分配状态 对象直到所有的都不能使用 字段已初始化。
以下是一些例子:
struct Bar
{
public int Val;
public Bar( int v ) { Val = v; }
}
public void Foo()
{
Bar z; // this is legal...
z.Val = 5;
Bar q = new Bar(5); // so is this...
q.Val = 10;
// using object initialization syntax...
Bar w = new Bar { Val = 42; }
}
结构数组与单个结构变量不同。当您声明一个结构类型的数组时,您要声明一个引用变量 - 因此,您必须使用new
运算符分配它:
Bar[] myBars = new Bar[10]; // member structs are initialized to defaults
如果你的struct有一个构造函数,你也可以选择使用数组初始化语法:
Bar[] moreBars = new Bar[] { new Bar(1), new Bar(2) };
你可以比这更复杂。如果您的struct
具有基本类型的隐式转换运算符,则可以将其初始化为:
struct Bar
{
public int Val;
public Bar( int v ) { Val = v; }
public static implicit operator Bar( int v )
{
return new Bar( v );
}
}
// array of structs initialized using user-defined implicit converions...
Bar[] evenMoreBars = new Bar[] { 1, 2, 3, 4, 5 };
答案 1 :(得分:0)
Struct是C#中的Value Type
,因此它使用堆栈内存而不是堆。
您可以以常规方式声明结构变量,例如int a = 90;
,
int是c#中的结构类型。
如果使用new
运算符,则将调用相应的构造函数。