如何给C#自动属性一个初始值?

我要么使用构造函数,要么恢复到旧语法。

使用构造函数:

class Person 
{
    public Person()
    {
        Name = "Initial Name";
    }
    public string Name { get; set; }
}

使用普通属性语法(具有初始值)

private string name = "Initial Name";
public string Name 
{
    get 
    {
        return name;
    }
    set
    {
        name = value;
    }
}

有更好的方法吗?


当前回答

当内联变量的初始值时,无论如何都会在构造函数中隐式完成。

我认为这种语法是C#中的最佳实践,最高可达5:

class Person 
{
    public Person()
    {
        //do anything before variable assignment

        //assign initial values
        Name = "Default Name";

        //do anything after variable assignment
    }
    public string Name { get; set; }
}

因为这样可以清楚地控制分配的顺序值。

从C#6开始,有一种新的方式:

public string Name { get; set; } = "Default Name";

其他回答

我认为这可以让SomeFlag默认为false。

private bool _SomeFlagSet = false;
public bool SomeFlag
{
    get
    {
        if (!_SomeFlagSet)
            SomeFlag = false;        

        return SomeFlag;
    }
    set
    {
        if (!_SomeFlagSet)
            _SomeFlagSet = true;

        SomeFlag = value;        
    }
}
private string name;
public string Name 
{
    get 
    {
        if(name == null)
        {
            name = "Default Name";
        }
        return name;
    }
    set
    {
        name = value;
    }
}
class Person 
{    
    /// Gets/sets a value indicating whether auto 
    /// save of review layer is enabled or not
    [System.ComponentModel.DefaultValue(true)] 
    public bool AutoSaveReviewLayer { get; set; }
}

在C#6.0中,这简直是小菜一碟!

您可以在Class声明本身和属性声明语句中执行此操作。

public class Coordinate
{ 
    public int X { get; set; } = 34; // get or set auto-property with initializer

    public int Y { get; } = 89;      // read-only auto-property with initializer

    public int Z { get; }            // read-only auto-property with no initializer
                                     // so it has to be initialized from constructor    

    public Coordinate()              // .ctor()
    {
        Z = 42;
    }
}

在C#(6.0)及更高版本中,您可以执行以下操作:

对于只读财产

public int ReadOnlyProp => 2;

对于可写和可读财产

public string PropTest { get; set; } = "test";

在当前版本的C#(7.0)中,您可以执行以下操作:(代码段显示了如何使用表达式体的get/set访问器,使其在与后台字段一起使用时更加紧凑)

private string label = "Default Value";

// Expression-bodied get / set accessors.
public string Label
{
   get => label;
   set => this.label = value; 
 }