【问题标题】:For structs, do I have to call the constructor explicitly in C#?对于结构,我是否必须在 C# 中显式调用构造函数?
【发布时间】:2010-05-05 03:35:14
【问题描述】:

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

【问题讨论】:

  • 不确定您是否还询问是否需要新建容器(例如 List),但答案是肯定的。 :)

标签: c# constructor struct explicit


【解决方案1】:

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

来自文档:

当您使用创建结构对象时 新的运算符,它被创建并 调用适当的构造函数。 与类不同,结构可以是 实例化而不使用新的 操作员。如果不使用 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 };

【讨论】:

  • 不好意思说,我用C#开发两年了,从来没有用过甚至没有遇到过隐式关键字!
【解决方案2】:

Struct 在 C# 中是 Value Type,因此它使用堆栈内存而不是堆内存。

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

int 是 c# 中的结构类型。

如果你使用new操作符,那么会调用对应的构造函数。

【讨论】:

    猜你喜欢
    • 2020-11-15
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 2014-06-17
    • 2020-09-29
    • 2014-11-06
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多