如何向结构添加多个构造函数?

How to add multiple constructors to a struct?

我有以下代码:

struct test {
    public int a;
    public int b;

    public test(int a) {
        this(a, null);
    }

    public test(int a, int b) {
        this.a = a;
        this.b = b;
    }
}

我想为 test 结构提供两个不同的构造函数,一个只需要传入 a ,另一个可以同时传入 ab.

此代码无效,因为它失败并出现一些错误:

对于 public test(int a) { 行:

Field 'test.a' must be fully assigned before control is returned to the caller

Field 'test.b' must be fully assigned before control is returned to the caller

对于 this(a, null); 行:

Method name expected.

The 'this' object cannot be used before all of its fields have been assigned

struct test {
    public int a;
    public int b;

    public test(int a) : this(a, 0) { }
    
    public test(int a, int b = 0) {
        this.a = a;
        this.b = b;
    }
}

您不能将 null 分配给 int。此外,您的变量名称不明确。您可以使用可选参数来实现您要查找的内容。或链接构造函数。

试试这个

struct Test 
{
    public readonly int a;
    public readonly int b;

    public Test(int a) : this()
    {
        this.a = a;
        this.b = 0;
    }

    public Test(int a, int b) : this()
    {
        this.a = a;
        this.b = b;
    }
}

另一种方法是使用带有一个构造函数的可选参数

    public Test(int a, int b = 0) : this()
    {
        this.a = a;
        this.b = b;
    }

或代替 0 使用 default(int),或仅 default

    public Test(int a) : this()
    {
        this.a = a;
        this.b = default(int);
    }

: this() 调用是 Microsoft 在使用 create constructor 工具时添加的,因此我将其添加到此处。我觉得只是提醒一下代码的reader,先分配栈中的space,再分配字段

我还添加了 readonly 关键字,因为可变结构是邪恶的,并强调需要在构造函数结束之前定义所有字段的要求。

或者您始终可以使用另一个构造函数中的一个构造函数

    public Test(int a) : this(a, 0)
    { }