参见英文答案 > Why can’t structs be declared as const? 4个
因为我在我的应用程序中的多个位置使用“System.Drawing.Color.Gainsboro”:
if (tb.BackColor.Equals(System.Drawing.Color.Gainsboro)) {
……我想让它成为一个常数.但当我尝试时:
const System.Drawing.Color PSEUDO_HIGHLIGHT_COLOR = System.Drawing.Color.Gainsboro;
…我得到了,“类型’System.Drawing.Color’不能声明为const”
???
解决方法:
唯一可以是const的类型是那些在C#中具有文字表示的类型,因为在编译时使用文字值替换对常量的引用.没有文字的方式来表示颜色(您只能通过工厂方法获得颜色,或者使用静态预先存在的颜色之一获得颜色).
但是,您可以使用静态只读变量来实现相同的效果.
static readonly Color PSEUDO_HIGHLIGHT_COLOR = Color.Gainsboro;
有关详细信息,请参阅C#语言规范的10.4节
The type specified in a constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type.
对于引用类型,唯一有效的值是字符串文字或null.
标签:c,constants,winforms,colors
来源: https://codeday.me/bug/20190711/1434821.html