Static propery or static readony field

风格不统一 提交于 2019-12-13 04:18:00

问题


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 :

  1. public static Color MyColor { get { return Color.Red; } }
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!