通过reflection创建委托

给定一个包含的程序集

namespace Foo{public class Bar;} 

如何在不编译时引用第一个程序集的情况下从另一个程序集创建Action

如果你使用

 Type barType = Type.GetType("Foo.Bar, whateverassembly"); Type actionType = typeof(Action<>).MakeGenericType(barType); 

actionType现在将代表Action 。 但是,要使用它,您需要继续使用reflection,因此您需要找到适合签名void(Foo.Bar)MethodInfo ,并调用Delegate.CreateDelegate来创建委托。 并且您需要Delegate.DynamicInvoke来执行它。

 Delegate call = Delegate.CreateDelegate(actionType, ...); ... call.DynamicInvoke(someBar); 

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

您不能在调用代码Action其命名为Action ,因为如果在编译时未引用该类型定义,则无法访问该类型定义。 由于Delegates是逆变的,您可以返回Action并使用它,或者使用Action ,其中IBar接口在引用的程序IBar定义,并由Foo.Bar实现。

如果确实返回了Action ,则必须通过reflection使用Foo.Bar成员(或者如果使用C#4.0则使用dynamic )或使用将其转换为Foo.Bar ,其中转换代码具有对程序集的引用Foo.Bar是定义的。