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

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

private bool isPopup = true; public bool IsPopup { get { return isPopup; } set { isPopup = value; } } 

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

 public bool IsPopup { get; set; } 

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

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

 public MyClass() { IsPopup = true; } 

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

 public bool IsPopup { get; set; } = true; // property initializer 

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

 public bool IsPopup { get; } = true; // read-only property with initializer 

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

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

VB.NET

 Property FirstName As String = "James" Property PartNo As Integer = 44302 Property Orders As New List(Of Order)(500) 

C#6.0及以上

 public string FirstName { get; set; } = "James"; public int PartNo { get; set; } = 44302; public List Orders { get; set; } = new List(500); 

C#5.0及以下

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

你试过DefaultValueAttribute吗?

 using System.ComponentModel; [DefaultValue(true)] public bool IsPopup { get { return isPopup; } set { isPopup = value; } } 

您可以使用如下所示的默认属性值

此方法的一个优点是您不需要检查 布尔类型的空值

 using System.ComponentModel; public class ClassName { [DefaultValue(true)] public bool IsPopup{ get; set; } }