c# - Cast int[] into MyType[] where MyType inherited from Enum? -


i try cast int array int[] rights array rights[], rights enum example... can other type rights inherited enum. got final type in type variable. can create enum[] array not final rights[] array methodinfo.invoke(obj,param.toarray()).

list<object> param = new list<object>(); parameterinfo pi = ... if (pi.parametertype.isarray && pi.parametertype.getelementtype().isenum) {     list<enum> enums = new list<enum>();     foreach (int in gettabint())     {         enums.add((enum)enum.toobject(pi.parametertype.getelementtype(), i));     }     param.add(enums.toarray()); // got enum[] not rights[] } 

thank helping me!

you need create array of appropriate type. since type isn't known @ compile time, must use array.createinstance(). can use helper method.

public array toenumarray(type type, icollection values) {     if (!typeof(enum).isassignablefrom(type))         throw new argumentexception(string.format("type '{0}' not enum", type));     var result = array.createinstance(type, values.count);     var = 0;     foreach (var value in values)         result.setvalue(enum.toobject(type, value), i++);     return result; } 

then use so:

parameterinfo pi = ...; if (pi.parametertype.isarray && pi.parametertype.getelementtype().isenum) {     var enumarray = toenumarray(pi.parametertype.getelementtype(), gettabint());     param.add(enumarray); } 

Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -