Enumeration extension methods

前端 未结 7 1180
长发绾君心
长发绾君心 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 08:01

    Another example of making Enum extension - but this time it returns the input enum type.

    public static IEnumerable toElementsCollection(this T value) where T : struct, IConvertible
        {
            if (typeof(T).IsEnum == false) throw new Exception("typeof(T).IsEnum == false");
    
            return Enum.GetValues(typeof(T)).Cast();
        }
    

    Example of usage:

    public enum TestEnum { A,B,C };
    
    TestEnum.A.toElementsCollection();
    

提交回复
热议问题