2017-07-24 76 views
3

我想要做这样的事情:枚举扩展方法来获取所有值

enum MyEnum { None, One, Two }; 

var myEnumValues = MyEnum.Values(); 

我的扩展方法:

 public static IEnumerable<T> Values<T>(this Enum enumeration) 
      where T : struct 
     => Enum.GetValues(typeof(T)).Cast<T>(); 

但它看起来是这样的:

MyEnum.None.Values<MyEnum>(); 

如何去做吧?

+0

你可以通过使用'this object value'去除* one *的一部分,然后删除'',然后在该值上使用'.GetType()'等,但是不能删除'None'在'MyEnum.None'中。这只是扩展方法的限制。 –

+0

您也可以使用'this T enumeration'来取消指定通用类型的需要。 – DavidG

+2

你可能会更好,只是适当地命名类和方法,所以你会得到像'EnumValues.Of ()' –

回答

3

扩展方法是应用于对象实例的静态方法。

MyEnum是一个类型,而不是一个实例,所以你不能添加扩展方法。

0

这样的结构如何?它模仿枚举工作的方式,但它必须实现Values方法的可能性:

public class WeatherType 
{ 
    private readonly string name; 

    public static readonly WeatherType Bad = new WeatherType("Bad"); 
    public static readonly WeatherType Good = new WeatherType("Good"); 
    public static readonly WeatherType Mid = new WeatherType("Mid"); 

    private static readonly WeatherType[] Values = { Bad, Good, Mid }; 

    public static WeatherType[] GetValues() 
    { 
     return (WeatherType[])Values.Clone(); 
    } 

    private WeatherType(string name) 
    { 
     this.name = name; 
    } 
} 

您现在有一个静态方法来获取可能的值的列表,像这样:

var values = WeatherType.GetValues();