静态属性或静态就绪字段 [英] Static propery or static readony field
问题描述
我有一些常量"的初始化属性/字段,我想知道以下哪一行最适合使用:
I have some intialized Property/Fields that are "constant" and I want to know which one of the following line is the best to use :
public static Color MyColor { get { return Color.Red;} }
public static readonly Color MyOtherColor = Color.Red;
(惰性)初始化后是否存在一些运行时差异?性能用途是否不同?
Is there some runtime differences after (lazy)initialization ? Are the performance usages differents ?
推荐答案
字段使用指南 建议对预定义的对象实例使用公共静态只读字段.例如:
The Field usage guidelines recommend using public static read-only fields for predefined object instances. For example:
public struct Color
{
// this is a predefined immutable instance of the containing Type
public static readonly Color Red = new Color(0x0000FF);
...
}
在你的情况下,我可能会使用一个属性:
In your case, I'd probably use a property:
public class MyClass
{
// Not a predefined instance of the containing Type => property
// It's constant today, but who knows, tomorrow its value may come from a
// configuration file.
public static Color MyColor { get { return Color.Red; } }
}
更新
当我看到你的答案时,它非常清楚,但是在 System.Drawing 中使用 ILSpy 向我展示了以下代码: public static Color Red { get { return new Color(KnownColor.Red);} }
It's crystal clear when I see your answer, but using ILSpy in System.Drawing shows me the following code: public static Color Red { get { return new Color(KnownColor.Red); } }
上面链接的指南(以颜色为例)适用于 .NET 1.1,并且可能已经演变.我个人认为使用属性不会出错..NET 4.0 Field Guidelines 类似,但使用 DateTime.MaxValue
和 DateTime.MinValue
作为预定义对象实例的示例.
The guidelines linked above (which use Color as an example) are for .NET 1.1 and have possibly evolved. Personally I don't think you can go wrong by using a property. .NET 4.0 Field Guidelines are similar, but use DateTime.MaxValue
and DateTime.MinValue
as examples of predefined object instances.
这篇关于静态属性或静态就绪字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!