参照DLL中的方法创建委托

问题描述:

我有DLL的一些方法。我在运行时加载它,我想创建委托给位于DLL中的方法。参照DLL中的方法创建委托

DLL:

public static Point Play(int[,] foo, int bar, int baz) { ... } 

// ... 

我要创建委托的播放方法。在DLL中可能有更多的方法。

代码:

private delegate Point PlayDel(int[,] foo, int bar, int baz); 

// ... 

Assembly ass = Assembly.LoadFile(pathToMyDLL); 
PlayDel dgt = // ??? 

你需要先找到包含此方法的类型,然后使用Delegate.CreateDelegate

Type type = ass.GetType("NameOfTypeContainingMethod"); 
PlayDel del = (PlayDel) Delegate.CreateDelegate(typeof(PlayDel), type, "Play"); 

或者,你可以得到MethodInfo并创建该委托:

Type type = ass.GetType("NameOfTypeContainingMethod"); 
MethodInfo method = type.GetMethod("Play"); 
PlayDel del = (PlayDel) Delegate.CreateDelegate(typeof(PlayDel), method); 

如果有多种方法所谓的Play,您可能需要拨打GetMethods()来代替并找到正确的(例如,首先通过参数类型)。