get-属性 中使用的表达式主体函数成员

Expression Bodied Function Members used in get-property

在编写 class 时,我可以通过两种方式在 Get-属性 中使用表达式主体函数:

class Person
{
    public string FirstName {get; set;}
    public string LastName {get; set;}

   public string FullName1 => $"{FirstName} {LastName}";
   public string FullName2 { get => $"{FirstName} {LastName}"; }
}

MSDN 关于 expression bodied function members

You can also use expression-bodied members in read-only properties as well:

public string FullName => $"{FirstName} {LastName}";

那么如果这个语法表示一个Get-属性的实现,那么第二个是什么意思呢?有什么不同?一个比另一个更受欢迎吗?

当你使用具有读写属性的表达式体成员时,它看起来像

public string Property {
    get => field;
    set => field = value;
}

事实上,即使您删除了 setter,这种语法也被接受是很自然的,拒绝它需要额外的努力,允许它也没有坏处。缩写 public string Property => field; 的意思完全相同,您可以自由选择您喜欢的任何形式。

这是一个风格和可读性的问题。

{ get => $"{FirstName} {LastName}"; } 的主要优点是您可以将它与 set {...} 结合使用。

它们是相同的。它们编译成相同的代码:

Person.get_FullName1:
IL_0000:  ldstr       "{0} {1}"
IL_0005:  ldarg.0     
IL_0006:  call        UserQuery+Person.get_FirstName
IL_000B:  ldarg.0     
IL_000C:  call        UserQuery+Person.get_LastName
IL_0011:  call        System.String.Format
IL_0016:  ret         

Person.get_FullName2:
IL_0000:  ldstr       "{0} {1}"
IL_0005:  ldarg.0     
IL_0006:  call        UserQuery+Person.get_FirstName
IL_000B:  ldarg.0     
IL_000C:  call        UserQuery+Person.get_LastName
IL_0011:  call        System.String.Format
IL_0016:  ret         

只是不同形式的表示法,允许您也以相同的格式提供 set