当前位置:首 页 > 攻城湿 >Windows > 查看文章

EnumParser实现

Windows 你是第1726个围观者 0条评论 供稿者: 标签:, ,

先看例子:

public enum Color
{
  Red,
  Blue,
  Gray,
}
Color redColorEnum = EnumParser<color>.Parse("Red");
</color>


以下是实现代码:

public static class EnumParser<t>
{
  private static readonly Dictionary<string , T> _dictionary = new Dictionary</string><string , T>();

  static EnumParser()
  {
    if (!typeof(T).IsEnum)
      throw new NotSupportedException("Type " + typeof(T).FullName + " is not an enum.");

    string[] names = Enum.GetNames(typeof(T));
    T[] values = (T[]) Enum.GetValues(typeof(T));

    int count = names.Length;
    for(int i=0; i<count ; i++)
      _dictionary.Add(names[i], values[i]);
  }

  public static bool TryParse(string name, out T value)
  {
    return _dictionary.TryGetValue(name, out value);
  }

  public static T Parse(string name)
  {
    return _dictionary[name];
  }
}

这家伙很懒,什么都没写!

—— zhaorong

zhaorong
你可能也喜欢Related Posts
众说纷纭Comments
大眼 可爱 大笑 坏笑 害羞 发怒 折磨 快哭了 大哭 白眼 晕 流汗 困 腼腆 惊讶 憨笑 色 得意 骷髅 囧 睡觉 眨眼 亲亲 疑问 闭嘴 难过 淡定 抗议 鄙视 猪头
小提示:直接粘贴图片到输入框试试
努力发送中...
  • 评论最多
  • 最新评论
  • 随机文章
footer logo
未经许可请勿自行使用、转载、修改、复制、发行、出售、发表或以其它方式利用本网站之内容
Copyright © zhaorong All Rights Reserved. 滇ICP备15006105号-1