动态调用DLL中的方法 [英] Dynamically invoke a method in DLL
问题描述
我有一个包含一些方法(显示,隐藏和验证)的DLL。这里是其中的一种方法的一个例子隐藏(面板paneldynamic,字符型,列表< EventActions> EVENTLIST)
。所有的方法都包含相同的参数。
I have a DLL containing some methods (show, hide and validate). Here is an example of one of the methods hide(Panel paneldynamic, String id, List<EventActions> eventList)
. All methods contains the same parameters.
现在我已经提到了我的DLL我的主要形式,我怎么能动态调用的方法之一,在运行时?
Now I have referenced the my DLL on my main form, how can I dynamically invoke one of the methods at runtime?
推荐答案
您需要使用反射。首先,加载程序集(注意,这个假设您已经导入<$ C $ C>的System.Reflection ):
You'll need to use reflection. First, load the assembly (note that this assumes you've imported System.Reflection
):
Assembly a = Assembly.LoadFile(pathToTheDll);
获得通过完全限定名称包含方法类型:
Get the type containing the method by fully-qualified name:
Type t = a.GetType("Some.Class");
现在,获得方法:
MethodInfo m = t.GetMethod("hide"); // For example
然后,所有你需要做的就是调用它:
Then, all you have to do is invoke it:
m.Invoke(null, new object[] { /* parameters go here */ });
第一个参数调用
是实例。如果你的类是静态
,使用空
,否则,你就需要提供使用创建的类型的实例 Assembly.CreateInstance
。
The first argument to Invoke
is the instance. If your class is static
, use null
, otherwise, you'll need to supply an instance of the type created using Assembly.CreateInstance
.
这篇关于动态调用DLL中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!