[英]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.