简体   繁体   English

Expression-Bodied Function成员用于get-property

[英]Expression Bodied Function Members used in get-property

When writing a class, I can use an Expression bodied function in a Get-property in two ways: 在编写类时,我可以通过两种方式在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 about expression bodied function members 关于表达身体功能成员的 MSDN

You can also use expression-bodied members in read-only properties as well: 您也可以在只读属性中使用表达式身体成员:

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

So if this syntax represents the implementation of a Get-property, what does the second one mean? 因此,如果此语法表示Get属性的实现,那么第二个是什么意思? What is the difference? 有什么不同? Is one preferred above the other? 一个优先于另一个吗?

Those are identical. 那些是相同的。 They compile to the same code: 他们编译成相同的代码:

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         

Just different form of notation, allowing you to also provide set in the same format. 只是不同形式的表示法,允许您以相同的格式提供set

It's a matter of style and readability. 这是风格和可读性的问题。

The main advantage of { get => $"{FirstName} {LastName}"; } { get => $"{FirstName} {LastName}"; }的主要优点{ get => $"{FirstName} {LastName}"; } { get => $"{FirstName} {LastName}"; } is that you can combine it with a set {...} . { get => $"{FirstName} {LastName}"; }是,你可以用它结合set {...}

When you use expression-bodied members with read-write properties, it looks like 当您使用具有读写属性的表达式身体成员时,它看起来像

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

The fact that this syntax is accepted even if you remove the setter is only natural, it would take extra effort to reject that and there is no harm in allowing it. 即使你删除了setter这个语法也被接受的事实是很自然的,它需要额外的努力来拒绝它,并且允许它没有任何害处。 The short form public string Property => field; 短格式public string Property => field; means exactly the same thing and you are free to choose whichever form you prefer. 意思完全相同,你可以自由选择你喜欢的形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM