c# - 只读变量 VS 只读属性

标签 c# oop

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/

相关文章:

oop - Fortran 2003/2008 子类的数据继承

javascript - Promise 完成后调用另一个原型(prototype)方法

c# - 在存在触发器的情况下从 linq 到 sql 向 sql server 插入行时出错

c# - CS0144 - C# - 无法创建抽象类或接口(interface)的实例

c# - 获取具有特殊扩展名的文件的 TreeView

c# - 加载 SNI.dll 失败

c# - 在这种特定情况下,我应该如何建模我的代码以最大限度地重用代码?

Node.js:如何从抽象类中获取 'inherit'?

c# while 中的两个语句

ios - 类继承、重写方法以及访问父类(super class)存储的属性