以下代码在 C# 5.0 中有效:
private static String _prefix;
public static String Prefix
{
get { return _prefix; }
set {_prefix = (value == String.Empty) ? "abc_" : value;}
}
我尝试使用默认初始化在 C#6 中将其编写得更简洁。 ( https://msdn.microsoft.com/en-us/magazine/dn802602.aspx )
以下代码在 C# 6.0 中有效(但逻辑不同)
public String Prefix { get; set; } = "abc_";
我尝试过:
公共(public)字符串前缀 { get;放; } 值 == String.Empty ? “abc_”:值
但是由于名称“值”在当前上下文中不存在
而失败如何修复此错误?
我想要做的是将属性设置为“abc_”(如果它为 null 或空),并且如果它已经有一个值,请不要触摸它。
最佳答案
这段代码不是关于默认初始化,而是关于防止 string.Empty
被设置为初始化后的值。
private static String _prefix;
public static String Prefix
{
get { return _prefix; }
set {_prefix = (value == String.Empty) ? "abc_" : value;}
}
此代码行将在初始化时一次设置默认值,但不会阻止稍后设置string.Empty
。
public String Prefix { get; set; } = "abc_";
What I'm trying to do is set the property to "abc_" if it's null or empty and if it already has a value, don't touch it.
简化 C# 6 中的第一个代码的唯一方法是使用表达式体。不仅要检查字符串是否为空,还要检查它是否为空,您可以使用 string.IsNullOrEmpty。
private static String _prefix;
public static String Prefix
{
get => _prefix;
set => _prefix = string.IsNullOrEmpty(value) ? "abc_" : value;
}
关于C# 6.0 默认初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44628396/