public static string BoldStartTag { get { return "<B>"; } }
对比
public static readonly string BoldStartTag = "<B>";
或
public const string BoldStartTag = "<B>";
哪个更受欢迎?我会认为只读/常量变量,因为我没有在属性中进行任何计算(只是返回)。此外,C# 编译器将为 readonly 属性弹出一个方法,而 readonly 变量将只是 IL 中的一个变量。
你的想法?
最佳答案
Jeff Atwood 在 Properties vs Public Variables 上写了一篇文章不久前。
我认为这里需要考虑的一些最有趣的点是他在更新中提到的:
- Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
- You can't databind against a variable.
- Changing a variable to a property is a breaking change.
关于c# - 只读变量 VS 只读属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2948533/