kejames 學習筆記本

這裡是Kejames的筆記本,歡迎各位網友給予指教,謝謝。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Another version for the missing method: Enum.TryParse (in C#)

Posted on 2008-06-28 01:25  Kejames  阅读(561)  评论(0)    收藏  举报

http://mironabramson.com/blog/post/2008/03/Another-version-for-the-missing-method-EnumTryParse.aspx

The 'TryParse' methods for all types are very useful and I'm using them all the time. It's very surprising that Microsoft didn't include in the Framework a method that can be very useful: Enum.TryParse. A lot of coders find themself writing from time to time  'parsing' methods for their enums. Something like that:

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;
    }
}...

 Thats work fine, but you need to write such 'parsing' method for each enum you have.  The Enum class have it's own 'parsing' method (that luckly have 'IgnoreCase' flag), but not a TryParse method. The commonly fix around is to put the Enum.Parse method inside Try & Catch, what is, of cource, give bad performance in case of failure. The Enum class have also a method 'IsDefined' that return an indication if a value is exists in the enum. unfortunately, this method doesn't have an  'IgnoreCase' flag.

So, trying to put all this 'knowledge' together, I wrote my own generic version for 'Enum.TryParse' method that is also ignore case and not using 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;
    }
}

The line 'string strTypeFixed = strType.Replace(' ', '_');' is because I was getting the data from third party WebService that send the enum strings with spaces, what is not allowed in enum, so my enums had '_' instead of  spaces.

To parse a ImageType (from the example above) just use it like this:

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