在运行时更换.NET类型类型、NET

2023-09-04 23:22:29 作者:痴迷.

我已经定义的类型 T 在编译时.NET程序集,我已经实例化一个对象 my_t 因为这类型的实例

I have a .NET assembly which has defined a type T at compile time, and I have instantiated an object my_t as an instance of this type.

我想知道是否有可能在.NET中使用运行时编译服务重新编译这个类,那么新的类定义加载到当前执行的程序集,所以当我调用方法关闭 my_t ,它们将使用新的code。

I am wondering if it is possible in .NET to use the runtime compiler services to re-compile this class, then load the new class definition into the currently executing assembly, so when I call methods off of my_t, they will use the new code.

我不改变任何方法的签名,只是方法​​体。

I am not changing the signatures of any of the methods, just the method bodies.

任何.NET大师那里知道这是可能的吗?在此先感谢您的帮助!

Any .NET gurus out there know if this is possible? Thanks in advance for any help!

推荐答案

一个.NET对象不能在运行时改变类型;它在CLR的一个基本假设。

A .NET object can't change type at runtime; it's a fundamental assumption in the CLR.

这是一些建议:

写$ C $下 T 将呼叫转移到正确的类型进行细分。它可以转发到都在运行时编译的,如果你想要一个类型。 使用某种方面为导向的或动态代理框架来自动(1)为您 如果这种转移是不适合的,我相信这是一个.NET分析API提供给本机,可以让你拦截了JIT过程。我所知道的这是,像NCover工具能够注入自己的机器code这个样子。 Write the code for T to forward calls to the right type as appropriate. It can forward to a type that gets compiled at runtime if you want to. Use some kind of aspect-orientated or dynamic proxy framework to automate (1) for you If this kind of forwarding isn't suitable, I believe there is a .NET profiling API available to native that lets you intercept the JIT process. All I know of this is that tools like NCover are able to inject their own machine code this way.