使用"Expression Bodied Functions and Properties"有什么好处?

The*_*ira 11 c# c#-6.0

我确实看到很多人使用这个新功能,但使用这些表达式有什么好处?

示例:

public override string ToString() => string.Format("{0}, {1}", First, Second);

public string Text =>
string.Format("{0}: {1} - {2} ({3})", TimeStamp, Process, Config, User);
Run Code Online (Sandbox Code Playgroud)

这个问题是不同的这一个,因为如果性能和效率也发生变化,但也对编译后的代码(IL代码)的区别,我不只是问,如果这是最好的做法,应在现实世界中使用.

这个问题也不主题,因为我要求的是现实生活中的企业经验,而不是建议.因此,不建议,但解释为什么你会或为什么你不会使用该功能以及你有什么经验!

Mac*_*akM 8

它提供了更好的可读性并节省了代码中的一些空间.它更好.

  • 尽管它使方法更简洁,但我发现扩展的方法声明更容易理解,因为它们在类成员之间保持一致的缩进。 (4认同)

The*_*ira 5

回答我的问题之一。我已经测试了一下,如果IL代码相同,结果如下:

static void Main(string[] args)
{
    Console.WriteLine(MyClass.GetTexted);
}

class MyClass
{
    private static string dontTouchMe = "test";

    public static string GetTexted { get { return dontTouchMe + "1"; } }

    //public static string GetTexted => dontTouchMe + "1";
}
Run Code Online (Sandbox Code Playgroud)

...将生成相同的 IL代码:

00993376  call        [random value]
0099337B  mov         dword ptr [ebp-40h],eax  
0099337E  mov         ecx,dword ptr [ebp-40h]  
00993381  call        71886640  
00993386  nop  
        }
00993387  nop  
00993388  lea         esp,[ebp-0Ch]  
0099338B  pop         ebx  
0099338C  pop         esi  
0099338D  pop         edi  
0099338E  pop         ebp  
0099338F  ret  
Run Code Online (Sandbox Code Playgroud)

[random value]部分是唯一已更改的代码,这很有意义,因为每次编译时它都会更改。


我仍在学校学习,所以我只能从我的角度回答其他问题(这不是企业观点):

  • 由于代码更紧凑,更易读,因此“表达有力的功能和属性”确实是一个好习惯。(感谢@Wazner@MacakM

  • 使用它们也很有意义,因为它们看起来更模块化,更像是OOP代码


Tin*_*wor 5

正文表达式仅提供一种紧凑且更简洁的方式来声明只读属性.
从性能的角度来看,你写这个:

public bool MyProperty {
    get {
        return myMethod();
    }
}

private bool myMethod() {return true;}
Run Code Online (Sandbox Code Playgroud)

或这个:

public bool MyProperty => myMethod();
private bool myMethod() {return true;}
Run Code Online (Sandbox Code Playgroud)

没有区别,因为它IL以相同的方式被翻译成了.
但请注意这一点:body表达式是deafult在Visual Studio 2015和更新版本上可用的功能,但是如果你想在旧的VS版本中使用,你需要从nuget安装C#6.0

  • 您也可以在方法声明中使用Expression-body`public bool MyProperty => myMethod(); private bool myMethod()=> true;` (2认同)