以下两个属性声明之间是否存在性能/内存使用差异,是否应首选?
public bool Foo => true;
public bool Foo { get; } = true;
Run Code Online (Sandbox Code Playgroud)
另外,如果使用不同的不可变值(例如字符串)替换布尔值,情况是否会发生变化?
我写这个类作为例子
class Program
{
public bool A => true;
public bool B { get; } = true;
}
Run Code Online (Sandbox Code Playgroud)
通过反射,我反编译了程序集并得到了这段代码
class Program
{
// Fields
[CompilerGenerated, DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly bool <B>k__BackingField = true;
public bool A
{
get
{
return true;
}
}
public bool B
{
[CompilerGenerated]
get
{
return this.<B>k__BackingField;
}
}
}
Run Code Online (Sandbox Code Playgroud)
因此,正如@Fruchtzwerg 提到的,两种方法都具有相同的返回值的方式,但不同之处在于 getter 方法的实现,因为一种返回值ture,另一种返回具有 value的字段true。
谈到性能和内存,第一种方式似乎更好,但如果您只需要这个属性,true我建议使用const.