mardi 6 septembre 2016

How can I create an IEnumerable from an enum using its System.Type (C#)

I am trying to unserialize enum types.

I need a method with this prototype:

private static object CSVConvertParam(string value, System.Type t);

So I can use it this way:

enum MyEnum { val1=0, val2=1, val3=2 ...}
...
System.Type enumType = typeof(MyEnum);
...
var unserializedVal = CSVConvertParam("val3", enumType );

I have read this nearly similar question: How can I create an IEnumerable from an enum

But in my case, the type is unknown at compile time.

It must be very close of this:

private static object CSVConvertParam(string value, System.Type t)
{
 int enumIndex = ( (IEnumerable<????>) t.GetEnumValues()).ToList().IndexOf( value);
return  (Enum)Enum.ToObject(t, enumIndex);

}

except that I would need to know the concrete type that t represents to have the (IEnumerable) cast to work. Is there a way to solve this?

Thx in advance.





Aucun commentaire:

Enregistrer un commentaire