gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:19:24 26 4
gpt4 key购买 nike

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/

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