如何在 ASP.NET 中设置自动实现属性的默认值
我开始知道 C# 3.0 附带了自动实现属性的新功能,我喜欢它,因为我们不必在此声明额外的私有变量(与早期的属性相比),之前我使用的是属性,即
private bool isPopup = true;
public bool IsPopup
{
get
{
return isPopup;
}
set
{
isPopup = value;
}
}
现在我已将其转换为自动实现的属性,即
public bool IsPopup
{
get; set;
}
我想将此属性的默认值设置为 true,甚至在 page_init 方法中也不使用它,我尝试过但没有成功,任何人都可以解释如何执行此操作吗?
I came to know that C# 3.0 comes with a new feature of Auto-Implemented Properties,I liked it as we don't have to declare extra private varible in this (compare to earlier property), earlier I was using a Property i.e.
private bool isPopup = true;
public bool IsPopup
{
get
{
return isPopup;
}
set
{
isPopup = value;
}
}
Now I've converted it into Auto-Implemented property i.e.
public bool IsPopup
{
get; set;
}
I want to set the default value of this property to true without using it not even in page_init method, I tried but not succeeded, Can anyone explain how to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以在默认构造函数中初始化属性:
使用 C# 6.0,可以像普通成员字段一样在声明处初始化属性:
现在甚至可以创建一个真正的只读自动属性,您可以直接初始化该属性,也可以在其中初始化该属性。构造函数,但未在类的其他方法中设置。
You can initialize the property in the default constructor:
With C# 6.0 it is possible to initialize the property at the declaration like normal member fields:
It is now even possible to create a real read-only automatic property which you can either initialize directly or in the constructor, but not set in other methods of the class.
为自动属性指定的属性不适用于支持字段,因此默认值的属性不适用于此类属性。
但是,您可以初始化自动属性:
VB.NET
C# 6.0 及更高版本
C# 5.0 及更低版本
不幸的是,6.0 以下的 C# 版本不支持支持这一点,因此您必须在构造函数中初始化自动属性的默认值。
Attributes specified for an auto property do not apply to the backing field, so an attribute for a default value won't work for this type of property.
You can, however, initialize an auto property:
VB.NET
C# 6.0 and above
C# 5.0 and below
Unfortunately, C# versions below 6.0 do not support this, so you have to initialize the default values for auto properties in the constructor.
您是否尝试过 DefaultValueAttribute
Have you tried DefaultValueAttribute
您可以使用默认属性值,如下所示
此方法的一个优点是您不需要检查布尔值<的空值 /strong> 类型
You can use default property value like below
One advantage of this method is you don't need to check null values for Boolean types