通过反射创建委托

dss*_*539 6 c# reflection delegates .net-3.5

给定一个包含的程序集

namespace Foo{public class Bar;}
Run Code Online (Sandbox Code Playgroud)

如何Action<Foo.Bar>在编译时不引用第一个程序集而从另一个程序集创建?

Rub*_*ben 10

如果你使用

Type barType = Type.GetType("Foo.Bar, whateverassembly");
Type actionType = typeof(Action<>).MakeGenericType(barType);
Run Code Online (Sandbox Code Playgroud)

actionType现在代表Action<Foo.Bar>.但是,要使用它,您需要使用反射,因此您需要找到MethodInfo符合签名的void(Foo.Bar)调用,并调用Delegate.CreateDelegate以创建委托.你需要Delegate.DynamicInvoke执行它.

Delegate call = Delegate.CreateDelegate(actionType, ...);
...
call.DynamicInvoke(someBar);
Run Code Online (Sandbox Code Playgroud)

有些东西告诉我,这不是你想的......