[英]How can I create an IEnumerable from an enum using its System.Type
我試圖反序列化枚舉類型。
我需要一個這個原型的方法:
private static object CSVConvertParam(string value, System.Type t);
所以我可以這樣使用它:
enum MyEnum { val1=0, val2=1, val3=2 ...}
...
System.Type enumType = typeof(MyEnum);
...
var unserializedVal = CSVConvertParam("val3", enumType );
我已經讀過這個幾乎相似的問題: 如何從枚舉中創建IEnumerable
但在我的情況下,類型在編譯時是未知的。
它必須非常接近:
private static object CSVConvertParam(string value, System.Type t)
{
int enumIndex = ( (IEnumerable<????>) t.GetEnumValues()).ToList().IndexOf( value);
return (Enum)Enum.ToObject(t, enumIndex);
}
除了我需要知道t代表的具體類型才能使(IEnumerable)轉換工作。
有辦法解決這個問題嗎?
編輯:我試圖制作一個可以解決這個問題的通用版本:
private static object CSVConvertParam<T>(string value)
{
if (typeof(T).IsEnum)
{
int enumIndex = ((IEnumerable<T>) typeof(T).GetEnumValues()).ToList().IndexOf(value); // this actually does not work and needs to be worked on
return (Enum)Enum.ToObject(t, enumIndex);
}
}
但假設我設法使這個方法正確工作,那么編譯器似乎不允許我調用它,因為我的意思是:
string[] propertiesNames = ...;
PropertyInfo propertyInfo = properties.FirstOrDefault(p => p.Name.Equals(propertiesNames[i]));
paramValue = CSVConvertParam<propertyInfo.PropertyType>(objectPropertiesValues[i]);
編譯器不接受CSVConvertParam:“無法找到類型或命名空間propertyInfo ...”我再次假設,propertyInfo.PropertyType是System.Type,而<>期望具體類型。
試試Enum.GetNames(type)
。 這將返回一個string[]
然后您可以在該數組中找到字符串的索引。
但是,正如其他人所說,你可能只是重新發明了Enum.Parse(Type, string)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.