【问题标题】:.NET 3.5 doesn't have enum.tryparse, how to safely parse string to enum then? [duplicate].NET 3.5 没有 enum.tryparse,那么如何安全地将字符串解析为 enum? [复制]
【发布时间】:2012-10-10 21:12:45
【问题描述】:

可能重复:
How to TryParse for Enum value?

我正在使用没有 Enum.TryParse 的 .net 3.5。

那么我怎样才能安全地将字符串解析为枚举呢?

我在 .net 4.0 中这样做:

SomeEnum someEnum;
if (Enum.TryParse(someString, true, out someEnum))
{
  //
}

【问题讨论】:

标签: c# enumeration


【解决方案1】:

您可以使用 Enum.GetNames(...).Contains 然后使用 Enum.Parse

【讨论】:

    【解决方案2】:

    缺少方法的另一个版本:Enum.TryParse(在 C# 中)

    所有类型的“TryParse”方法都非常有用,我一直在使用它们。令人惊讶的是,微软没有在框架中包含一个非常有用的方法:Enum.TryParse。许多编码人员发现自己不时为他们的枚举编写“解析”方法。类似的东西:

    public enum ImageType
    {
        Jpg,
        Gif,
        Png
    }
    
    public static ImageType ParseImagetype(string typeName)
    {
        typeName = typeName.ToLower();
        switch (typeName)
        {
            case "Gif":
                return ImageType.Gif;
            case "png":
                return ImageType.Png;
            default:
            case "jpg":
                return ImageType.Jpg;
        }
    }...
    

    这很好,但是您需要为您拥有的每个枚举编写这样的“解析”方法。 Enum 类有它自己的“解析”方法(幸运的是有“IgnoreCase”标志),但没有 TryParse 方法。通常的解决方法是将 Enum.Parse 方法放在 Try & Catch 中,当然,如果失败,性能会很差。 Enum 类还有一个方法“IsDefined”,如果枚举中存在值,则返回指示。不幸的是,此方法没有“IgnoreCase”标志。

    因此,为了将所有这些“知识”放在一起,我为“Enum.TryParse”方法编写了自己的通用版本,该方法也忽略大小写,不使用 try & catch:

    public static bool EnumTryParse<T>(string strType,out T result)
    {
        string strTypeFixed = strType.Replace(' ', '_');
        if (Enum.IsDefined(typeof(T), strTypeFixed))
        {
            result = (T)Enum.Parse(typeof(T), strTypeFixed, true);
            return true;
        }
        else
        {
            foreach (string value in Enum.GetNames(typeof(T)))
            {
                if (value.Equals(strTypeFixed, StringComparison.OrdinalIgnoreCase))
                {
                    result = (T)Enum.Parse(typeof(T), value);
                    return true;
                }
            }
            result = default(T);
            return false;
        }
    }
    

    行'string strTypeFixed = strType.Replace(' ', '');'是因为我从发送带有空格的枚举字符串的第三方 WebService 获取数据,这是枚举中不允许​​的,所以我的枚举有 '' 而不是空格。

    要解析 ImageType(来自上面的示例),只需像这样使用它:

    ImageType type;
    if (Utils.EnumTryParse<ImageType>(typeName, out type))
    {
        return type;
    }
    return ImageType.Jpg;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 2013-08-16
      • 1970-01-01
      • 1970-01-01
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多