我爲我的問題尋找解決方案,但到目前爲止我無法弄清楚如何去做。如何將一個整數標記爲枚舉的通用列表?
我需要獲取由int
值標記的enum
的值列表。
我能夠在特定情況下做到這一點,但我想爲泛型枚舉器創建一個通用函數。
爲specicic情況下,代碼是:
IList<MyEnum> EnumList= new List<MyEnum>();
MyEnum EnumIUseToFlag= (MyEnum)intToParse;
foreach (MyEnumitem in Enum.GetValues(typeof(MyEnum)))
{
if (EnumIUseToFlag.HasFlag(item))
{
EnumList.Add(item);
}
}
現在,對於一般的方法我試圖像:
public static IList<T> GetFlaggedValues<T>(int intValue) where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
IList<T> listToReturn = new List<T>();
Enum enumToParse = Enum.Parse(typeof(T), intValue.ToString()) as Enum;
foreach (T item in Enum.GetValues(typeof(T)))
{
// here I am not able to cast item in the integer
//values i need to use in order to flag my enum
}
return listToReturn;
}