Defining colors as constants in C#

房东的猫 提交于 2019-12-01 02:29:46

Only literals can be defined as const. The difference is, that const values are hard-bakened into the assemblies that uses it. Should their definition change, then the call sites doesn't notice unless they get recompiled.

In contrast, readonly declares a variable in a way that it cannot be reassigned after outside the constructor (or static constructor in case of a static readonly variable).

So, you have no other way then to use readonly here, since Color is a struct, and no primitive data type or literal.

A const field is a compile time constant - you actually need code to run to determine the value of Color.Orange though, internally probably defined as

public static readonly Color Orange = new Color(...);

Since this cannot be computed at compile time, your only option is readonly which is set at runtime.

Also check out this article.

You can define a static Colors like this:

// tested with C# 5.0
static const Color ERROR = Color.FromArgb(0, 255,0);
static const Color MYPOOL = Color.FromKnownColor(KnownColor.Aqua);

You could at the very least make 'em static. A read-only field is otherwise just that, a field, that can only be assigned to during initilization. It makes no guarantees about the represented value being "read-only".

Aside from the technical aspects that others have mentioned (that const values are replaced at compile-time in the places they are used, and are required to be literals rather than static readonly values which are assigned and referenced at runtime) there is a semantic issue to consider.

The reason const values are replaced at compile-time is that const really does mean "constant" - as in a value that will never, ever change such as pi or e. That's why it's safe to replace them at compile-time, because the name represents a forever unchanging value.

The fact that you state...

The purpose is simply to have a single location in which to change all of the colors for logging purposes.

...indicates that these are not semantically constant, and thus should not be defined as const even if it were possible to do so.

This is fine, and you can't do any better (as the compiler tells you).

But do make them static, if they are not already.

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