SomeValue {get;} = true; 之间的区别vs SomeValue => 真;在属性中

Difference between SomeValue {get;} = true; vs SomeValue => true; in Properties

在 C# 中,您可以用两种看起来非常相似的方式声明 属性:

public string SomeProperty => "SomeValue";

public string SomeProperty { get; } = "SomeValue";

这两者有区别吗? (忽略 "SomeValue" 不是一个非常有趣的值这一事实,它可能是方法调用的结果或其他任何可以表达两种形式之间差异的结果)。

在您的示例中没有功能差异,因为您总是 returning 一个常量值。但是,如果值可以更改,例如

public string SomeProperty => DateTime.Now.ToString();

public string SomeProperty { get; } = DateTime.Now.ToString();

第一个会在每次调用 属性 时执行表达式。每次访问 属性 时,第二个都会 return 相同的值,因为该值是 在初始化 时设置的。

在 C#6 之前的语法中,每个的等效代码为

public string SomeProperty
{
    get { return DateTime.Now.ToString();}
}

private string _SomeProperty = DateTime.Now.ToString();
public string SomeProperty 
{ 
    get {return _SomeProperty;} 
}