如何在ASP.NET中为自动实现的属性设置默认值

Imr*_*zvi 25 c# asp.net automatic-properties default-value

我开始知道C#3.0带有Auto-Implemented Properties的新功能,我喜欢它,因为我们不必在此声明额外的私有变量(与之前的属性相比),之前我使用的是属性,即

private bool isPopup = true;
public bool IsPopup
{
    get
    {
      return isPopup;
    }
    set
    {
      isPopup = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我已将其转换为Auto-Implemented属性即

public bool IsPopup
{
    get; set;
}
Run Code Online (Sandbox Code Playgroud)

我想将此属性的默认值设置为true而不使用它甚至在page_init方法中,我尝试但没有成功,任何人都可以解释如何做到这一点?

slf*_*fan 44

您可以在默认构造函数中初始化该属性:

public MyClass()
{
   IsPopup = true;
}
Run Code Online (Sandbox Code Playgroud)

使用C#6.0,可以在声明中初始化属性,就像普通成员字段一样:

public bool IsPopup { get; set; } = true;  // property initializer
Run Code Online (Sandbox Code Playgroud)

现在甚至可以创建一个真正的只读自动属性,您可以直接初始化或在构造函数中初始化,但不能在类的其他方法中设置.

public bool IsPopup { get; } = true;  // read-only property with initializer
Run Code Online (Sandbox Code Playgroud)

  • 不知何故,你必须初始化你的财产.由于没有后备字段(由编译器生成),因此没有其他选项.在这种情况下,我写了完整的属性,幸运的是你得到intellisense这样做. (2认同)

Ed *_*gne 7

为auto属性指定的属性不适用于支持字段,因此默认值的属性不适用于此类属性.

但是,您可以初始化自动属性:

VB.NET

Property FirstName As String = "James"
Property PartNo As Integer = 44302
Property Orders As New List(Of Order)(500)
Run Code Online (Sandbox Code Playgroud)

C#6.0及以上

public string FirstName { get; set; } = "James";
public int PartNo { get; set; } = 44302;
public List<Order> Orders { get; set; } = new List<Order>(500);
Run Code Online (Sandbox Code Playgroud)

C#5.0及以下

遗憾的是,低于6.0的C#版本不支持此功能,因此您必须在构造函数中初始化auto属性的默认值.