我确实看到很多人使用这个新功能,但使用这些表达式有什么好处?
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代码)的区别,我不只是问,如果这是最好的做法,应在现实世界中使用.
这个问题也不 是主题,因为我要求的是现实生活中的企业经验,而不是建议.因此,不建议,但解释为什么你会或为什么你不会使用该功能以及你有什么经验!
回答我的问题之一。我已经测试了一下,如果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]
部分是唯一已更改的代码,这很有意义,因为每次编译时它都会更改。
我仍在学校学习,所以我只能从我的角度回答其他问题(这不是企业观点):
正文表达式仅提供一种紧凑且更简洁的方式来声明只读属性.
从性能的角度来看,你写这个:
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
归档时间: |
|
查看次数: |
8906 次 |
最近记录: |