How can I create a closure that uses a reflected type argument? Targeting .net 3.5
Without reflection I would have
void Main()
{
int i = 0;
Action<Foo> doSomething = (foo) => i += foo.GetNumber();
var myFoo = new Foo();
myFoo.UseFoo(doSomething);
Console.WriteLine(i);
}
class Foo
{
public int GetNumber() { return 4; }
public void UseFoo(Action<Foo> doSomething)
{
doSomething(this);
}
}
When Foo is a type obtained via reflection from another assembly, how would I set doSomething?
void Main()
{
Type fooType = GetType("Foo");
int i = 0;
object doSomething = // ???;
var myFoo = Activator.CreateInstance(fooType);
fooType.GetMethod("UseFoo").Invoke(myFoo, new object[] { doSomething });
Console.WriteLine(i);
}
I used both DocXcz and Nikola Anusev’s answers to get to this
Basically I needed to use a generic helper method to do the conversion of the
Action<object>to anAction<T>determined at runtime