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

下面带有关键字的代码工作正常,但我想像在 C# 中static一样创建以下属性。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 }

        };

  }

}

}


守着一只汪
浏览 90回答 2
2回答

吃鸡游戏

你不能。static readonly和之间存在差异const,因为无论何时代码引用 a&nbsp;const,都会将其值const直接烘焙到它被引用的位置。因此 aconst只能是数字、布尔值、字符串或空值。

HUWWW

从文档:常量可以是数字、布尔值、字符串或空引用。...局部常量或常量字段的初始化器必须是可以隐式转换为目标类型的常量表达式。常量表达式是可以在编译时完全求值的表达式。因此,引用类型常量的唯一可能值是字符串和空引用。话虽如此,您不能将const其用于任何非编译时文字的内容。这尤其包括用 初始化的所有内容new。
打开App,查看更多内容
随时随地看视频慕课网APP