我有一些接口和实现该接口的类:
public interface IWhatever {
bool Value { get; set;}
}
public class Whatever : IWhatever {
public bool Value { get; set; }
}
现在,C#
是否允许Value
有一些默认值,而不使用任何后备字段?
我有一些接口和实现该接口的类:
public interface IWhatever {
bool Value { get; set;}
}
public class Whatever : IWhatever {
public bool Value { get; set; }
}
现在,C#
是否允许Value
有一些默认值,而不使用任何后备字段?
更新
从C# 6 (VS2015)开始,这种语法是完全有效的。
public bool Value { get; set; } = true;
设置只读属性的值就像原样。
public bool Value { get; } = true;
旧的,C# 6之前的回答
提醒:以下内容不适用于兴奋的人:以下代码将不起作用。
你是在问:"我能做到这个吗?"
public bool Value { get; set; } = true;
不可以,你需要在类的构造函数中设置默认值。
根据文档,如果没有指定初始值,它默认为 false。
但是,如果你想用除了 false
以外的初始值来实例化它,可以按照以下方式操作:
public interface IWhatever
{
bool Value { get; set;}
}
public class Whatever : IWhatever
{
public bool Value { get; set; }
public Whatever()
{
Value = true;
}
}
默认值现在是false
。要将其设置为true
,请在构造函数中设置。
public class Whatever : IWhatever
{
public bool Value { get; set; }
public Whatever()
{
this.Value = true;
}
}
默认情况下,Value
将为false
,但可以在构造函数中初始化。
你不能将Value
设置为除属性本身默认值以外的任何其他默认值。你需要在Whatever
的构造函数中分配默认值。
你可以在构造函数中设置默认值。
//constructor
public Whatever()
{
Value = true;
}
public bool Value { get; set; }