2017-07-24 53 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();