有没有办法运行系统中建立一个新的类型? [英] Is there a way to build a new type during Runtime?

查看:134
本文介绍了有没有办法运行系统中建立一个新的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要问一个可能听起来不可思议的问题。

I am going to ask a question that might sound weird.

有没有办法运行过程中建立一个新的类?或者至少,一个新的属性添加到现有的类。

Is there a way to build a new class during Runtime? Or at least, add a new property to an existing class.

我的意思是创建不存在与现有类的不是一个实例的类。我可以在以后使用反射来加载和使用这个类。

I mean creating a class that doesn't exist and not an instance of an existing class. I could later on use reflections to load and use this class.

推荐答案

添加属性到现有的类型是不可能的,但你可以创建一个使用Reflection.Emit的一种新的运行时。这是pretty的复杂的东西,它是这样的:

Adding a property to an existing type is not possible, but you can create a new type at runtime using Reflection.Emit. It's pretty complicated stuff, and it goes something like this:

AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(
      assemblyName , AssemblyBuilderAccess.Run, assemblyAttributes);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("ModuleName");
TypeBuilder typeBuilder = moduleBuilder.DefineType(
      "MyNamespace.TypeName" , TypeAttributes.Public);

typeBuilder.DefineDefaultConstructor(MethodAttributes.Public);

// Add a method
newMethod = typeBuilder.DefineMethod("MethodName" , MethodAttributes.Public);

ILGenerator ilGen = newMethod.GetILGenerator();

// Create IL code for the method
ilGen.Emit(...);

// ...

// Create the type itself
Type newType = typeBuilder.CreateType();

这code是只是一个样本。它可能包含错误。

This code is just a sample. It could contain errors.

您还可以通过使用系统。codeDOM编译C#源$ C ​​$ C运行时生成类,但我不知道了很多关于这一点。

You can also generate classes by compiling C# source code at runtime using System.CodeDom, but I don't know a lot about that.

这篇关于有没有办法运行系统中建立一个新的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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