如何从dll文件创建实例并运行其方法? [英] how to create instance from dll file and run its method?

查看:88
本文介绍了如何从dll文件创建实例并运行其方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我将一些dll文件附加到我的程序中,并将这些名称设置为menustrip项目。我想点击这些项目时自动运行dll。所以,这些dll文件实现了一个接口dll!

Hi,
I append some dll files to my program, and set these names as item to menustrip. I want when click on these items run dll automaticly. so, these dll files implement an interface dll!

private void Form1_Load(object sender, EventArgs e) { foreach (var file in Directory.GetFiles(@"F:\tamrin\calcut\calcut\bin\Debug\plugin\", "*.dll")) { s = file.ToString(); var asm = Assembly.LoadFrom(file.ToString());
                foreach (var type in asm.GetTypes())
                {
                        AssemblyName asn = asm.GetName();
                        string[] b = asn.ToString().Split(',');
                        menu.Items.Add(b[0]);

// how to create instance from dll file and run its method?//
                    }
                }
            }

推荐答案

.NET framework(从4开始)有一个通过接口解决可扩展性的部分 - 它称为托管扩展性框架 [ ^ ] ...

它使您能够定义扩展点(如菜单)并根据这些DLL实现的接口加载DLL ...

我写了一篇关于它通过可扩展的Web应用程序显示ide:可扩展的Web应用程序 [ ^ ]
.NET framework (since 4) has a part that addresses extensiblity via interfaces - it called Managed Extensibility Framework[^]...
It enables you to define extension points (like menu) and load DLLs based on interfaces implemented by those DLLs...
I wrote an article about it that show the ides via a extensible web application: Extensible Web Application[^]


尝试
Type t = asn.GetType(file.ToString() + "ClassName");  //Classname is class to be instantiated
var methodInfo = t.GetMethod("MyMethod", new Type[] { typeof(byte[]), typeof(int) });//myMethod is method to be instantiated
var o = Activator.CreateInstance(t);
var result = methodInfo.Invoke(o, params);//invoke the method



加载程序集后,加载class然后调用方法。


Once the assembly is loaded, load the class and then invoke the method.


请看我过去的答案:

访问驻留在插件dll中的自定义对象 [ ^ ],

收集来自程序集的类型由字符串表示 [ ^ ],

现有实例的C#Reflection InvokeMember [ ^ ],

动态加载用户控件 [ ^ ]。



-SA
Please see my past answers:
Access a custom object that resides in plug in dll[^],
Gathering types from assemblies by it's string representation[^],
C# Reflection InvokeMember on existing instance[^],
Dynamically Load User Controls[^].

—SA


这篇关于如何从dll文件创建实例并运行其方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆