<分区>
在 C# 中,您可以用两种看起来非常相似的方式声明属性:
public string SomeProperty => "SomeValue";
对比
public string SomeProperty { get; } = "SomeValue";
这两者有区别吗? (忽略“SomeValue”不是一个非常有趣的值这一事实,它可能是方法调用的结果或其他任何可以表达两种形式之间差异的结果)。
<分区>
在 C# 中,您可以用两种看起来非常相似的方式声明属性:
public string SomeProperty => "SomeValue";
对比
public string SomeProperty { get; } = "SomeValue";
这两者有区别吗? (忽略“SomeValue”不是一个非常有趣的值这一事实,它可能是方法调用的结果或其他任何可以表达两种形式之间差异的结果)。
最佳答案
在您的示例中,没有功能差异,因为您总是返回一个常量值。但是,如果值可能会发生变化,例如
public string SomeProperty => DateTime.Now.ToString();
对比
public string SomeProperty { get; } = DateTime.Now.ToString();
第一个会在每次调用属性时执行表达式。第二个将在每次访问属性时返回相同的值,因为该值是在初始化时设置的。
在 C#6 之前的语法中,每个的等效代码是
public string SomeProperty
{
get { return DateTime.Now.ToString();}
}
对比
private string _SomeProperty = DateTime.Now.ToString();
public string SomeProperty
{
get {return _SomeProperty;}
}
关于c# - SomeValue {get;} = true; 之间的区别vs SomeValue => 真;在属性中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39260137/