Enumeration extension methods

前端 未结 7 1208
长发绾君心
长发绾君心 2020-12-01 07:09

In vs2008, is it possible to write an extension methods which would apply to any enumeration.

I know you can write extension methods against a specific enumeration,

7条回答
  •  臣服心动
    2020-12-01 07:43

    FYI Here is a great example of an Enum Extension method that I have been able to use. It implements a case insensitive TryParse() function for enums:

    public static class ExtensionMethods
    {
        public static bool TryParse(this Enum theEnum, 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;
            }
        }
    }
    

    You would use it in the following manner:

    public enum TestEnum
    {
        A,
        B,
        C
    }
    
    public void TestMethod(string StringOfEnum)
    {
        TestEnum myEnum;
        myEnum.TryParse(StringOfEnum, out myEnum);
    }
    

    Here are the two sites that I visited to help come up with this code:

    Case Insensitive TryParse for Enums

    Extension methods for Enums

提交回复
热议问题