4

问题是关于结构的。当我声明一个结构类型变量/对象(不知道哪个更适合)或一个数组或结构列表时,我是否必须像对象一样显式调用构造函数,还是像变量一样声明就足够了?

4

2 回答 2

13

C# 中的结构可以在调用或不调用构造函数的情况下创建。在没有调用构造函数的情况下,结构的成员被初始化为默认值(基本上为零),并且在struct其所有字段都被初始化之前不能使用。

从文档中:

当您使用 new 运算符创建结构对象时,它会被创建并调用相应的构造函数。与类不同,结构可以在不使用 new 运算符的情况下进行实例化。如果不使用 new,则这些字段将保持未分配状态,并且在所有字段都初始化之前无法使用该对象。

下面是一些例子:

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

如果您的结构有构造函数,您还可以选择使用数组初始化语法:

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 };
于 2010-05-05T03:43:17.130 回答
0

Struct 是Value TypeC# 中的一个,因此它使用堆栈内存而不是堆内存。

您可以以常规方式声明结构变量,例如int a = 90;

int 是 c# 中的结构类型。

如果您使用new运算符,则将调用相应的构造函数。

于 2010-05-05T06:13:39.280 回答