创建动态实现接口的类 [英] Creating a class implementing an interface dynamically

查看:184
本文介绍了创建动态实现接口的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个代码,该代码允许用户加载程序集(DLL文件),在所述程序集中选择一个接口,而不是生成一个继承该接口的类以及所有必需方法的存根.

I'm trying to write a code that allows a user to load an assembly (DLL file), choose an interface in said assembly, than generates a class inheriting that interface, with stubs for all required methods.

该类将生成到文件中或活动的VS会话中(该代码旨在在通过自定义模板创建项目的过程中初始化的IWizard内部使用).

The class would be generated either into a file or into an active VS session (the code is intended for use inside an IWizard initialized during project creation through a custom template).

我已经到达了接口的Type对象的地步,但是我很难确定下一部分,我已经考虑过循环运行接口的方法并将其复制到文本文件中,在适当的位置添加存根实现,但是我很确定有某种更好的方法,也许可以通过第三方工具?

I got to the point where I have the Type object of the interface, but I'm having a hard time figuring the next part, I've contemplated running across the interface's methods in a loop and copying them into a textual file, adding the stub implementations in the appropriate places but I'm pretty sure there's some better method, perhaps through a third party tool?

任何帮助,我们将不胜感激, 预先谢谢你.

Any help would be appreciated, Thank you in advance.

推荐答案

如果要在运行时创建新类型,则需要使用Reflection.Emit. Reflection.Emit允许您直接将中间语言发出到当前的AppDomain(或您愿意的话,也可以使用程序集)中.您可能想在内存中使用该类型,因此您可能不想创建实际的程序集.

If you want to create a new type at runtime, you'll need to use Reflection.Emit. Reflection.Emit allows you to emit Intermediate Language directly into the current AppDomain (or an assembly if you prefer.) You probably want to use the type in memory, so you may not want to create an actual assembly.

创建新类型是通过TypeBuilder类完成的.

Creating new type is done with the TypeBuilder class.

Codeproject有出色的介绍: http://www.codeproject.com/KB/dotnet/Creating_Dynamic_Types.aspx

Codeproject has an excellent introduction: http://www.codeproject.com/KB/dotnet/Creating_Dynamic_Types.aspx

更新:

已经提请我注意,目标是将C#代码文件添加到现有项目中.您仍然需要反映到程序集中并发出IL,但是随后您必须将IL去拼合"到C#中. Reflector是为此推荐的#1工具,尽管我不确定它是否可以以您想要的方式实现自动化.

It has been brought to my attention that the goal is to add a C# code file to an existing project. You would still need to reflect into the assembly and emit IL, but then you'd have to "dissasemble" the IL into C#. Reflector is the #1 recommended tool for this, though I'm not sure it can be automated in the way you want.

这篇关于创建动态实现接口的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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