【问题标题】:Constant instance in a static class静态类中的常量实例
【发布时间】:2014-07-31 15:53:21
【问题描述】:

我想做一个全局变量类,这是我的代码

public static class GLOBALVAR
{
    public static const Color DIFFRENCECOLOR = System.Drawing.Color.LightSalmon;
    public static const Color NOMATCHCOLOR = System.Drawing.Color.LightBlue;     
}

但这不想工作,我得到这个错误

The type 'System.Drawing.Color' cannot be declared const

有没有办法让这个工作。

【问题讨论】:

  • 你试过readonly而不是const吗?
  • 不知道那是一个命令

标签: c# class static constants


【解决方案1】:

您可以改用readonly

public static readonly Color DIFFRENCECOLOR = System.Drawing.Color.LightSalmon;

readonly 关键字表示你的变量 DIFFRENCECOLOR 只能在它的类 GLOBALVAR 的构造函数中修改。

它通常用于当你想在运行时声明一个“常量”,但它也适用于此目的。

http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2014-12-25
    • 1970-01-01
    相关资源
    最近更新 更多