Enumeration extension methods

前端 未结 7 1195
长发绾君心
长发绾君心 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条回答
  •  Happy的楠姐
    2020-12-01 07:41

    Sometimes there is a need to convert from one enum to another, based on the name or value of the enum. Here is how it can be done nicely with extension methods:

    enum Enum1 { One = 1, Two = 2, Three = 3 };
    enum Enum2 { Due = 2, Uno = 1 };
    enum Enum3 { Two, One };
    
    Enum2 e2 = Enum1.One.ConvertByValue();
    Enum3 e3 = Enum1.One.ConvertByName();
    Enum3 x2 = Enum1.Three.ConvertByValue();
    
    public static class EnumConversionExtensions
    {
        public static T ConvertByName(this Enum value)
        {
            return (T)Enum.Parse(typeof(T), Enum.GetName(value.GetType(), value));
        }
    
        public static T ConvertByValue(this Enum value)
        {
            return (T)((dynamic)((int)((object)value)));
        }
    }
    

提交回复
热议问题