色彩定义在C#中的常量 [英] Defining colors as constants in C#
问题描述
我已经设置了一些默认的颜色在C#WinForms应用程序,像这样:
I've set up some default colors in a C# winforms application like so:
readonly Color ERROR = Color.Red;
readonly Color WARNING = Color.Orange;
readonly Color OK = Color.Green;
据我所知,只读本质上是我的目的,一个常数。如果我试图将它们定义为常量,编译器表明它必须是一个编译时间常数,它的颜色是没有的。
As far as I am aware, readonly is essentially a constant for my purposes. If I attempt to define these as constants, the compiler indicates that it must be a compile-time constant, which Color is not.
我是不是好离开这些原样,或者是有一些方法来定义这些常量,我应该知道的?
Am I good leaving these as-is, or is there some way to define these constants that I should be aware of?
的(的目的很简单,就是有一个单独的位置来改变所有的颜色进行日志记录。)的
推荐答案
只有文字可以被定义为常量
。所不同的是,常量
值硬bakened 为使用它的组件。应在其定义的变化,然后调用点不会注意到,除非他们得到重新编译。
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.
这篇关于色彩定义在C#中的常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!