枚举扩展方法获取所有值

时间:2017-07-24 11:04:28

标签: c#

我想做这样的事情:

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>(); 

怎么做?

2 个答案:

答案 0 :(得分:4)

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

MyEnum是一种类型,而非实例,因此您无法为其添加扩展方法。

答案 1 :(得分: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();
相关问题