gpt4 book ai didi

c# - 只获取具有常量值的属性,是否自动属性?

转载 作者:太空狗 更新时间:2023-10-29 23:05:17 24 4
gpt4 key购买 nike

以下两个属性声明之间是否存在性能/内存使用差异,应该首选一个吗?

public bool Foo => true;

public bool Foo { get; } = true;

此外,如果将 bool 值替换为不同的不可变值(例如字符串),情况是否会发生变化?

最佳答案

我写了这个类作为例子

class Program
{
public bool A => true;
public bool B { get; } = true;
}

通过反射我反编译了程序集并得到了这段代码

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;
}
}
}

正如@Fruchtzwerg 提到的,这两种方式返回值的方式相同但是,区别在于getter 方法的实现,因为一个返回值true 和其他返回值为 true 的字段。

谈论性能和内存第一种方式似乎更好,但如果您只需要此属性为 true 我建议使用 const

关于c# - 只获取具有常量值的属性,是否自动属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45533538/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com