Replacing the shared list

so I'm trying to set the field list<>inside the object with a new one list<>. this list can be of any type, so use generics.

I get a compile-time error, 'cannot convert expression System.Collections.Generic.List<object>to type System.Collections.Generic.IEnumerable<T>' Is there a way to make this work?

private void MyGenericMethod<T>(FieldInfo field)
{   
    field.SetValue(obj, new List<T>(newObjectList));    // new List<T> allObjects.ConvertAll<IEnumerable>) ???
}
+3
source share
1 answer

I'm with Damien. The problem should be newObjectList because there is no problem passing the List of generic type to SetValue, since it takes two arguments of type Object

public void SetValue(
Object obj,
Object value
)

If you create a new list and fill it with another collection, it will ask for IEnumerable, so you should try something like

field.SetValue(obj, new List<T>(newObjectList as IEnumerable<T>));

At least during compilation it will not cause errors

+2
source

All Articles