Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取所有值的枚举扩展方法_C# - Fatal编程技术网

C# 获取所有值的枚举扩展方法

C# 获取所有值的枚举扩展方法,c#,C#,我想这样做: enum MyEnum { None, One, Two }; var myEnumValues = MyEnum.Values(); var values = WeatherType.GetValues(); 我的扩展方法: public static IEnumerable<T> Values<T>(this Enum enumeration) where T : struct =>

我想这样做:

enum MyEnum { None, One, Two };

var myEnumValues = MyEnum.Values();
var values = WeatherType.GetValues();
我的扩展方法:

        public static IEnumerable<T> Values<T>(this Enum enumeration)
             where T : struct
         => Enum.GetValues(typeof(T)).Cast<T>();
公共静态IEnumerable值(此枚举枚举)
其中T:struct
=>Enum.GetValues(typeof(T)).Cast();
但看起来是这样的:

MyEnum.None.Values<MyEnum>(); 
MyEnum.None.Values();

怎么做

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


MyEnum
是一个类型,而不是一个实例,因此不能向其添加扩展方法。

这样的构造怎么样?它模仿enum的工作方式,但也可以实现
方法:

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;
    }
}
现在,您有了一个静态方法来获取可能值的列表,如下所示:

enum MyEnum { None, One, Two };

var myEnumValues = MyEnum.Values();
var values = WeatherType.GetValues();

您可以通过使用
此对象值
,删除
,然后使用
.GetType()
等该值来删除其中的一部分,但您无法删除
MyEnum.None中的
None
。这只是扩展方法的一个限制。您也可以使用
这个T枚举
来代替指定泛型类型的需要。您最好只适当地命名类和方法,这样您就可以得到类似
EnumValues.of()