10

我想知道以下 C# 代码:

struct Structure
{
    public Structure(int a, int b)
    {
        PropertyA = a;
        PropertyB = b;
    }
    public int PropertyA { get; set; }
    public int PropertyB { get; set; }
}

它没有编译错误“在分配所有字段之前不能使用'this'对象”。对于类似的类,它的编译没有任何问题。

可以通过重构以下内容来使其工作:

struct Structure
{
    private int _propertyA;
    private int _propertyB;

    public Structure(int a, int b)
    {
        _propertyA = a;
        _propertyB = b;
    }

    public int PropertyA
    {
        get { return _propertyA; }
        set { _propertyA = value; }
    }

    public int PropertyB
    {
        get { return _propertyB; }
        set { _propertyB = value; }
    }
}

但是,我认为将自动属性引入 C# 的全部目的是避免编写以后的代码。这是否意味着自动属性与结构无关?

4

3 回答 3

21

在 C# 6 中,这完全消失了;问题中的代码编译得很好。


虽然 Stefan 有答案而不是解决问题,但我必须建议你不要使用可变结构 - 它咬你。可变结构是邪恶的。

IMO,这里的“正确”修复很简单:

struct Structure
{
    public Structure(int a, int b)
    {
        propertyA = a;
        propertyB = b;
    }
    private readonly int propertyA, propertyB;
    public int PropertyA { get { return propertyA; } }
    public int PropertyB { get { return propertyB; } }
}
于 2011-02-17T13:03:03.493 回答
15

您需要先调用默认构造函数,如下所示:

struct Structure
{
    public Structure(int a, int b) : this()
    {
        PropertyA = a;
        PropertyB = b;
    }
    public int PropertyA { get; set; }
    public int PropertyB { get; set; }
}
于 2011-02-17T12:58:42.253 回答
8

如您所见,PropertyA在构造函数中引用时,您访问的是this对象,编译器不允许这样做,因为您的字段尚未初始化。

为了解决这个问题,您需要找到一种方法来初始化字段。一种方法是您的示例:如果您不使用自动属性,则字段是显式的,您可以初始化它们。

另一种方法是让您的构造函数调用另一个初始化字段的构造函数。结构总是隐式地有一个无参数的构造函数,它将其字段初始化为零,所以使用它:

public Structure(int a, int b)
    : this()
{
    PropertyA = a;
    PropertyB = b;
}
于 2011-02-17T13:01:31.963 回答