C# 如何设置自动属性的默认值?
我有一些接口和实现该接口的类:
public interface IWhatever {
bool Value { get; set;}
}
public class Whatever : IWhatever {
public bool Value { get; set; }
}
现在,C#
是否允许 Value
在不使用某些支持字段的情况下拥有一些默认值?
I have some interface and class implementing that interface:
public interface IWhatever {
bool Value { get; set;}
}
public class Whatever : IWhatever {
public bool Value { get; set; }
}
Now, does C#
allow the Value
to have some default value without using some backing field?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
更新
从 C# 6 (VS2015) 开始,此语法
与为只读属性设置值一样
完全有效C# 6 之前的旧答案
剧透警告令人兴奋的性质:以下代码将不起作用
您是否在问“我可以这样做吗?”
不,你不能。您需要在类的构造函数中设置默认值
Update
As of C# 6 (VS2015) this syntax is perfectly valid
as is setting a value for a readonly property
The old, pre C# 6 answer
Spoiler alert for those of an excitable nature: The following code will not work
Are you asking, "Can I do this?"
No, you can't. You need to set the default value in the constructor of the class
根据文档,如果其后面没有任何内容,则默认为 false。
但是,如果您希望使用除
false
以外的初始值实例化它,您可以这样做:If there's nothing behind it, it defaults to false, according to the documentation.
However, if you want it to be instantiated with an initial value other than
false
, you can do that this way:目前的默认值为
false
。要使其为true
,请在构造函数中设置它。The default value right now is
false
. To make ittrue
, set it in the constructor.默认情况下,
Value
将为false
,但它可以在构造函数中初始化。By default
Value
would befalse
but it can be initialized in the constructor.您不能将
Value
设置为除属性中数据类型本身的默认值之外的任何其他默认值。您需要在Whatever
的构造函数中分配默认值。You can not set
Value
to any other default value than the default value of the datatype itself at the property. You need to assign the default value in the constructor ofWhatever
.您可以在构造函数中设置默认值。
顺便说一句 - 使用自动属性,您仍然有一个支持字段,它只是由编译器为您生成(语法糖)。
You can set a default value in the constructor.
By the way - with automatic properties, you still have a backing field, it just gets generated for your by the compiler (syntactic sugar).