自动属性和结构

时间:2011-02-17 12:56:43

标签: c# .net properties struct automatic-properties

我想知道以下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#的重点是避免编写后来的代码。这是否意味着自动属性与结构无关?

3 个答案:

答案 0 :(得分:20)

在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; } }
}

答案 1 :(得分:15)

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

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

答案 2 :(得分:8)

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

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

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

public Structure(int a, int b)
    : this()
{
    PropertyA = a;
    PropertyB = b;
}