c# – Expression-Bodied函数在get-property中使用的成员
作者:互联网
在编写类时,我可以通过两种方式在Get-property中使用Expression bodied函数:
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属性的实现,那么第二个是什么意思?有什么不同?一个优先于另一个吗?
解决方法:
那些是相同的.他们编译成相同的代码:
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
只是不同形式的表示法,允许您以相同的格式提供集合.