Enumeration extension methods

前端 未结 7 1211
长发绾君心
长发绾君心 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:44

    You can also implement conversion method as follows:

    public static class Extensions
    {
        public static ConvertType Convert(this Enum e)
        {
            object o = null;
            Type type = typeof(ConvertType);
    
            if (type == typeof(int))
            {
                o = Convert.ToInt32(e);
            }
            else if (type == typeof(long))
            {
                o = Convert.ToInt64(e);
            }
            else if (type == typeof(short))
            {
                o = Convert.ToInt16(e);
            }
            else
            {
                o = Convert.ToString(e);
            }
    
            return (ConvertType)o;
        }
    }
    

    Here is an example usage:

    int a = MyEnum.A.Convert();
    

提交回复
热议问题