gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:11:15 33 4
gpt4 key购买 nike

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

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

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

现在,C# 是否允许 Value 有一些默认值而不使用一些支持字段?/p>

最佳答案

更新

自 C# 6 (VS2015) 起,此语法完全有效

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

为只读属性设置一个值

public bool Value { get; } = true;

C# 6 之前的旧答案

剧透预警:以下代码无效

你是在问,“我可以这样做吗?”

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

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

关于C# 如何设置自动属性的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5885984/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com