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