以下在c#中使用expression-bodied语法的方式有区别吗?
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; }
两者之间有区别还是语法不同的等效代码?
就所有意图和目的而言,它们是相同的。它们的编译方式相同。你可以使用任何你喜欢的。
两种方式产生相同的 IL。
为了
using System;
public class Program {
public DateTime MyDate1 { get => DateTime.UtcNow; }
public DateTime MyDate2 => DateTime.UtcNow;
public void Main() {
}
}
两个版本的缩写 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()
}
public DateTime Date => DateTime.Now;
public DateTime Date { get => DateTime.Now; }
两者之间有区别还是语法不同的等效代码?
就所有意图和目的而言,它们是相同的。它们的编译方式相同。你可以使用任何你喜欢的。
两种方式产生相同的 IL。
为了
using System;
public class Program {
public DateTime MyDate1 { get => DateTime.UtcNow; }
public DateTime MyDate2 => DateTime.UtcNow;
public void Main() {
}
}
两个版本的缩写 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()
}