如何在C#中将静态属性转换为const属性?

时间:2019-04-01 11:46:32

标签: c# enums static const

下面带有关键字static的代码可以正常工作,但是我想在C#中将下面的属性设为constant

这样做的原因是整个项目的一致性。在现有项目中,所有永远不会更改值的属性都标记为const而不是static or static readonly

public class StatusList
{
public static Dictionary<DownloadStatus, int> DownlodStatusList
{
  get
  {
    return new Dictionary<DownloadStatus, int>()
        {
          { DownloadStatus.Preview, (int)DownloadStatus.Preview },
          { DownloadStatus.Active, (int)DownloadStatus.Active },
          { DownloadStatus.Expired, (int)DownloadStatus.Expired },
          { DownloadStatus.Inactive, (int)DownloadStatus.Inactive }
        };
  }
}
}

2 个答案:

答案 0 :(得分:1)

你不能。

static readonlyconst之间的区别在于,每当代码引用const时,const的值就会直接烘焙到被引用的位置。因此,const只能是数字,布尔值,字符串或null。

答案 1 :(得分:0)

来自docs

  

常量可以是数字,布尔值,字符串或null   参考。

     

...

     

常量局部或常量字段的初始化程序必须是   可以隐式转换为目标的常量表达式   类型。常量表达式是可以完全表示的表达式   在编译时进行评估。因此,唯一可能的值   引用类型的常量是字符串和空引用。

话虽如此,您不能将const用于不是编译时文字的任何内容。特别是其中包括所有用new初始化的内容。

相关问题