如何创建使用反射类型参数的闭包?针对 .net 3.5
如果没有反思,我会
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);
}
}
什么时候Foo
通过反射从另一个程序集获得类型,我将如何设置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);
}