struct bb
{
public int j = 8;
public int f;
public bb()
{
f = 88;
}
}
//main method
bb test;
我知道当我声明test
时,会调用无参数构造函数,但我猜只有被调用来将字段初始化为默认值并创建对象,但任何其他代码都是而不是在构造函数内像f=88;
一样运行。
我说得对吗?
这与C#11有关。
您可以为structs提供无参数构造函数,但不能保证它们被调用。考虑以下例子:
MyStruct s = default; // no ctor called
MyStruct[] s = new MyStruct[10]; // no ctor for the individual structs called
此外,如果您从非托管代码中获取结构,则不会对它们进行构造函数调用。