设置自动实现属性的默认值

Wus*_*iji 6 c# getter-setter

假设我有一个自动实现的属性

public int SheetNum { get; set; }
Run Code Online (Sandbox Code Playgroud)

无论如何都要将默认值设置SheetNum为1,所以它会是这样的

private int sheetNum = 1;

public int SheetNum
{
    set { this.sheetNum = value; }
    get { return this.sheetNum; }
}
Run Code Online (Sandbox Code Playgroud)

oɔɯ*_*ɯǝɹ 12

你快到了; 你只需要在构造函数中初始化值:

public class MyClass
{
    public MyClass()
    {
        Foo = 1;
    }

    public int Foo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)