如何使用System.Type从枚举中创建IEnumerable ?

本文关键字:创建 IEnumerable 枚举 何使用 System Type | 更新日期: 2023-09-27 18:06:04

我试图反序列化枚举类型。

我需要一个具有这个原型的方法:

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

我读过这个几乎类似的问题:如何从enum中创建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。键入while <>需要一个具体类型

如何使用System.Type从枚举中创建IEnumerable ?

尝试Enum.GetNames(type)。这将返回一个string[],然后您可以在该数组中找到您的字符串的索引。

但是,正如其他人所说,你可能只是重新发明了Enum.Parse(Type, string)