简体   繁体   English

C#构造函数初始化属性而不是字段?

[英]C# constructor initializing properties instead of fields?

Let's say that you have to use an constructor to initialize some fields... 假设您必须使用构造函数来初始化一些字段...

class Foo
{
    private int price;
    public Foo(int price)
    {
        this.price = price;
    }
}

I know that usually the constructor initializes some fields but what's the difference if I initialize properties with it. 我知道通常构造函数会初始化一些字段,但是如果我用它初始化属性有什么区别。 For example 例如

class Foo
{
    private int price { get; set; }
    public Foo(int price)
    {
        this.price = price;
    }
}

The code seems to work the same but my question is if this is good practice and should I do it ? 该代码似乎可以正常工作,但是我的问题是这是否是一种好的做法,我应该这样做吗?

It's fine for a constructor to initialize properties, but it's rarely useful to have private automatically-implemented properties. 构造函数初始化属性很好,但是拥有私有的自动实现属性很少有用。 I'd always use properties rather than fields for non-private state (whether those properties are automatically implemented or not) and private properties make sense when they're non-trivial, eg performing validation or some other computation. 我将始终使用属性而不是非私有状态的字段(无论这些属性是否自动实现),并且私有属性在不重要的情况下才有意义,例如执行验证或其他计算。 But I'd only turn a private field into a private automatically-implemented property if I wanted it for something like a reflection-based library that only understood properties. 但是,如果我希望将其用于仅基于属性的基于反射的库,则只能将私有字段转换为私有的自动实现的属性。

Absolutely fine. 绝对好

For more flexibility (eg if price isnt required ), you can also do this with object initialization: 为了获得更大的灵活性(例如,如果不需要 price),还可以通过对象初始化来实现:

class Foo
{
    public Foo() {}

    public int Price { get; set; }
}

var newFoo = new Foo(){ Price = someVariable };

See: https://msdn.microsoft.com/en-us/library/bb397680.aspx 请参阅: https : //msdn.microsoft.com/zh-cn/library/bb397680.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM