[英]Is there a difference between the following ways of using expression-bodied syntax in c#?
public DateTime Date => DateTime.Now;
public DateTime Date { get => DateTime.Now; }
Is there a difference between the two or is it equivalent code with different syntax?两者之间有区别还是具有不同语法的等效代码?
Both ways result in the same IL.两种方式都会导致相同的 IL。
For为了
using System;
public class Program {
public DateTime MyDate1 { get => DateTime.UtcNow; }
public DateTime MyDate2 => DateTime.UtcNow;
public void Main() {
}
}
the abbreviated IL for both versions is (I used https://sharplab.io ):两个版本的缩写 IL 是(我使用https://sharplab.io ):
// Methods
.method public hidebysig specialname
instance valuetype [mscorlib]System.DateTime get_MyDate1 () cil managed
{
// Method begins at RVA 0x2050
// Code size 6 (0x6)
.maxstack 8
IL_0000: call valuetype [mscorlib]System.DateTime [mscorlib]System.DateTime::get_UtcNow()
IL_0005: ret
} // end of method Program::get_MyDate1
.method public hidebysig specialname
instance valuetype [mscorlib]System.DateTime get_MyDate2 () cil managed
{
// Method begins at RVA 0x2050
// Code size 6 (0x6)
.maxstack 8
IL_0000: call valuetype [mscorlib]System.DateTime [mscorlib]System.DateTime::get_UtcNow()
IL_0005: ret
} // end of method Program::get_MyDate2
(...)
// Properties
.property instance valuetype [mscorlib]System.DateTime MyDate1()
{
.get instance valuetype [mscorlib]System.DateTime Program::get_MyDate1()
}
.property instance valuetype [mscorlib]System.DateTime MyDate2()
{
.get instance valuetype [mscorlib]System.DateTime Program::get_MyDate2()
}
For all intents and purposes they are the same.出于所有意图和目的,它们是相同的。 They are compiled the same.它们的编译方式相同。 You can use whichever you prefer.你可以使用任何你喜欢的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.