C# get属性中使用的表达式体函数成员

C# get属性中使用的表达式体函数成员,c#,c#-6.0,C#,C# 6.0,编写类时,我可以通过两种方式在Get属性中使用表达式体函数: class Person { public string FirstName {get; set;} public string LastName {get; set;} public string FullName1 => $"{FirstName} {LastName}"; public string FullName2 { get => $"{FirstName} {LastName}"

编写类时,我可以通过两种方式在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关于

也可以在只读属性中使用表达式体成员作为 嗯:


那么,如果这个语法表示Get属性的实现,那么第二个语法是什么意思?有什么区别?一个成员优先于另一个吗?

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

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

即使删除setter,这种语法也会被接受,这是很自然的,拒绝这种语法需要付出额外的努力,允许它也没有坏处。缩写形式的
公共字符串属性=>字段的意思完全相同,您可以自由选择您喜欢的格式。

这是风格和可读性的问题


{get=>$“{FirstName}{LastName}”}
的主要优点是可以将其与
集合{…}
组合使用

这些是相同的。它们编译为相同的代码:

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

我没有投反对票。。这个IL清楚地表明这两种方法返回相同的结果。我担心没有Get的方法会初始化一个字段,但是这个IL显示没有Get的版本也会调用Get@HaraldCoppoolse不必担心落选——“虚假的互联网点数”,我已经受够了:-)。很高兴这能直接回答你的问题。
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