C#: Invoking ForEach on a runtime-generated List<T>
c#, generics
Solution
You can do this:
var someGenericListYouCreated = ...;
var enumerable = someGenericListYouCreated as IEnumerable;
foreach(var foo in enumerable){
...
}
However, I'm working on way to do what you ACTUALLY want.
Edit:
Right, I hope this makes sense
private class Adapter<T>
{
private readonly Action<object> act;
public Adapter(Action<object> act){
this.act = act;
}
public void Do(T o)
{
act(o);
}
}
public static void Main(string[] args)
{
Type elementType = typeof(string);
var genericType = typeof(List<>).MakeGenericType(elementType);
var list = Activator.CreateInstance(genericType);
var addMethod = list.GetType().GetMethod("Add");
addMethod.Invoke(list, new object[] { "foo" });
addMethod.Invoke(list, new object[] { "bar" });
addMethod.Invoke(list, new object[] { "what" });
Action<object> printDelegate = o => Console.WriteLine(o);
var adapter = Activator.CreateInstance(typeof(Adapter<>).MakeGenericType(elementType), printDelegate);
var adapterDo = adapter.GetType().GetMethod("Do");
var adapterDelegate = Delegate.CreateDelegate(typeof(Action<string>), adapter, adapterDo);
var foreachMethod = list.GetType().GetMethod("ForEach");
foreachMethod.Invoke(list, new object[] { adapterDelegate });
}
What this does:
- Create a generic list (notice that it's using typeof(List<>)
- Add some strings to this list
- Create a new delegate, in this case an Action
- Create an instance of the adapter class
- Create a delegate of the type we need (Action) on the adapter class
- Call ForEach
Note, you don't necessarily have to use Action if you know the type you're going to be processing. You could very easily use an Action and it'll work...
Problem
I am generating a List<T> with a runtime-determined type parameter. I'd like to invoke the ForEach method to iterate over the items in the list: ``` //Get the type of the list elements Type elementType = GetListElementType(finfo); Type listType = Type.GetType("System.Collections.Generic.List`1[" + elementType.FullName + "], mscorlib", true); //Get the list var list = getList.Invoke(null, new Object[] { finfo.GetValue(myObject) }); MethodInfo listForEach = listType.GetMethod("ForEach"); //How do I do this? Specifically, what takes the place of 'x'? listForEach.Invoke(list, new object[] { delegate ( x element ) { //operate on x using reflection } }); ``` Given a MethodInfo corresponding to the ForEach method contained in my runtime-generated list type, what's the proper way to invoke it using an anonymous method? The above is my first stab, but don't know how to declare the type of the anonymous method's parameter.