【问题标题】:Better writing of a static Dictionary更好地编写静态词典
【发布时间】:2012-04-26 13:16:58
【问题描述】:

我正在保留一个静态字典来将存储在数据库中的简单整数映射到枚举值。

static Dictionary<long, EModelType> AttributeIdTypeToEModelType = 
   new Dictionary<long, EModelType>()
   {
      {1, EModelType.StatStr},
      {6, EModelType.HistStr},
      {7, EModelType.HistVal}
   };

最大的优势是当数据从数据库到达时,我使用它直接获取我的枚举值。

typ = AttributeIdTypeToEModelType[i];

这个系统的用法很简洁,但我觉得为此而有一个静态字典并不干净。

我没有机会尝试找到一种更简洁的方式来使用枚举器并覆盖它们的值。

有什么建议吗?

【问题讨论】:

    标签: c# dictionary enumeration


    【解决方案1】:

    您不需要Dictionary 即可将int 转换为适当的Enum 类型:

    var type = (EModelType)yourInt;
    

    或使用Enum.ToObject:

    var type = Enum.ToObject(typeof(EModelType) , yourInt);
    

    你可以用Enum.IsDefined检查它是否存在:

    if (! Enum.IsDefined(typeof(EModelType), yourInt)) throw new ArgumentException("Illegal type");
    

    【讨论】:

    • 太棒了!这就是我所缺少的。谢谢
    【解决方案2】:

    如果数据库中的值是字符串,则使用:

    EnumType x = (EnumType)Enum.Parse(typeof(EnumType), dr[0].ToString());
    

    如果数据库中的值为long,则使用:

    EnumType x = (EnumType)dr[0];
    

    如果您需要枚举的长值,请使用:

    long x = (long)EnumType.SomeEnum
    

    【讨论】:

    • 谢谢,您的第二个解决方案就是那个。
    【解决方案3】:

    您应该使用 int 支持类型定义您的枚举,如下所示:

    public enum EModelType : int
    {
        StatStr = 1,
        HistStr = 6,
        HistVal = 7
    }
    

    然后,就像 Tim 和 Chris 建议的那样,只需将整数从数据库转换或解析为您的枚举类型。

    【讨论】:

    • 这就是我所说的“使用枚举器并覆盖它们的值”是的
    猜你喜欢
    • 1970-01-01
    • 2015-08-02
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    • 2021-05-23
    • 2011-09-27
    相关资源
    最近更新 更多