C#如何为自动属性设置默认值?

7

我有一些接口和实现该接口的类:

public interface IWhatever {
   bool Value { get; set;}
}

public class Whatever : IWhatever {
   public bool Value { get; set; }
}

现在,C#是否允许Value有一些默认值,而不使用任何后备字段?


1
你的意思是可以指定默认值吗?比如在这个例子中,让Value默认为True? - Tomas McGuinness
6个回答

15

更新

从C# 6 (VS2015)开始,这种语法是完全有效的。

public bool Value { get; set; } = true;

设置只读属性的值就像原样。

public bool Value { get; } = true;

旧的,C# 6之前的回答

提醒:以下内容不适用于兴奋的人:以下代码将不起作用。

你是在问:"我能做到这个吗?"

public bool Value { get; set; } = true;

不可以,你需要在类的构造函数中设置默认值。


3
当我第一次看到那段代码示例时,我想:“不可能吧!你真的可以这样做吗?!” - Jon B
1
实际上,我认为这个答案应该更新,因为从C#6开始,这是有效的!(万岁!) - Moo-Juice
1
@Moo-Juice 谢谢你,牛奶大佬!我已经更新了答案 :) - Binary Worrier
1
@BinaryWorrier,我认为你应该获得一枚徽章,因为你在半个十年前就正确掌握了语法 :) - Moo-Juice

2

根据文档,如果没有指定初始值,它默认为 false。

但是,如果你想用除了 false 以外的初始值来实例化它,可以按照以下方式操作:

public interface IWhatever 
{
   bool Value { get; set;}
}

public class Whatever : IWhatever 
{
    public bool Value { get; set; }

    public Whatever()
    { 
        Value = true;
    }
}

我的意思是,比如将其设置为“true”。 - Yippie-Ki-Yay
@Yippie 不,C#不允许你这样做。如果你想要它有一个初始值但没有后备字段,你需要在构造函数中设置它。 - George Stocker

1

默认值现在是false。要将其设置为true,请在构造函数中设置。

public class Whatever : IWhatever 
{
   public bool Value { get; set; }
   public Whatever()
   {
       this.Value = true;
   }
}

0

默认情况下,Value将为false,但可以在构造函数中初始化。


0

你不能将Value设置为除属性本身默认值以外的任何其他默认值。你需要在Whatever的构造函数中分配默认值。


0

你可以在构造函数中设置默认值。

//constructor
public Whatever()
{
   Value = true;
}

public bool Value { get; set; }

顺便提一下 - 使用自动属性时,您仍然有一个后备字段,只是由编译器为您生成(语法糖)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接