末尾带有“ this()”的结构构造函数与另一个不带“ struct()”的结构构造函数有什么区别?

时间:2019-04-11 17:17:50

标签: c# struct constructor

假设我们有这两种结构...

public struct Example
{
    public int Number { get; set; }

    public Example(int Number)
    {
        Number = number;
    }
}

和:

public struct Example
{
    public int Number { get; set; }

    public Example(int number) : this()
    {
        Number = number;
    }
}

您会看到有一个结构体,其末尾有**this()**,而另一个没有。

两者之间有什么区别?

4 个答案:

答案 0 :(得分:3)

调用this()将所有字段初始化为零。 C#编译器要求在构造函数中初始化所有结构字段。因此,如果您不想指定所有字段,则应调用this()。

将不会编译:

struct A
{
    public int field1;
    public string field2;

     public A(string str)
     {
         field2 = str;
     }
}

礼物:

  

错误CS0171,必须完全分配字段'A.field1',然后才能将控制权返回给调用方...

可以吗

struct A
{
    public int field1;
    public string field2;

    public A(string str) : this()
    {
        field2 = str;
    }
}

很奇怪,但仍然可以:

struct A
{
    public int field1;
    public string field2;

    public A(string str)
    {
        this = new A(); // in structs 'this' is assignable
        field2 = str;
    }
}

struct A
{
    public int field1;
    public string field2;

    public A(string str)
    {
        this = default(A); // in structs 'this' is assignable
        field2 = str;
    }
}

答案 1 :(得分:2)

已更新

对于班级

区别在于,调用this()的构造函数还将调用不带参数的类的构造函数。因此,例如,如果这是您的课程:

public class Example
{
    public int Number { get; set; }

    public Example(int number) : this()
    {
        Number = number;
    }
    public Example()
    {
        Console.WriteLine("Hello");
    }
}

然后包含this()的内容也会显示“ Hello”。您可以通过这种方式将构造函数链接在一起,以实现代码重用。

对于结构

您不能在结构中添加空的构造函数,因此添加this()不会带来任何好处。感谢vendettamit唤醒了我疲惫的大脑。

答案 2 :(得分:2)

在您的示例中,行为没有变化,因为this()调用了未定义结构的无参数构造函数。

请注意,在C#6.0及更高版本中,您无法re-define结构的无参数构造函数,因此,如果这样做:

public struct Example
{
    public Example() // compile error in c# 6.0 and up
    {
    }
}

您将得到一个编译错误。更多详细信息here

在较旧的C#版本中,您可以重新定义无参数构造函数,这意味着您可以通过修改无参数构造函数来向参数化构造函数注入额外的行为。

除此之外,由于为this()构造函数生成了额外的IL代码,因此可能会在理论上影响性能。

Example..ctor:
IL_0000:  ldarg.0     
IL_0001:  initobj     UserQuery.Example
IL_0007:  nop         
IL_0008:  ldarg.0     
IL_0009:  ldarg.1     
IL_000A:  call        UserQuery+Example.set_Number
IL_000F:  nop         
IL_0010:  ret 

答案 3 :(得分:1)

没有区别。 this()将调用无参数构造函数,这是定义所必须的结构,除非您重新定义它并自定义其行为,否则它将不会做任何事情。如果使用struct,则不允许您定义自己的无参数构造函数;可以使用class es。

但是,请注意,在复杂的构建场景中,即当对象公开大量具有不同参数的构造函数时,构造函数链接是DRY的便捷工具。