问题
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 ?
回答1:
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; } }
}
UPDATE
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); } }
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.
回答2:
If they are constants, then use a constant:
public const Color MyColor = Color.Red;
In answer to the question, here's a good read on the msdn forums: Memory consumption: static fields vs static properties
Edit:
As Joe pointed out in the comments, Color cannot be declared a constant because it is not a compile time constant.
A better answer to this question is answered by Joe.
In the end, there will be no noticeable difference between using a static readonly field vs property. Use whatever fits best with the situation.
来源:https://stackoverflow.com/questions/10899285/static-propery-or-static-readony-field