编程方法添加到类? [英] Programmatically add methods to class?

查看:138
本文介绍了编程方法添加到类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我处理的API,有一类万元的方法,我知道这些方法做,他们只是代理到web服务。

I'm dealing with an API, that has a class of million methods, I know what these methods do, they're just proxies to a web-service.

该API使用反射调用适当的方法名(不要问我为什么它这样做的方式)。

The API internally calls these proxy methods using reflection invoking the appropriate method name (don't ask me why it's done this way).

有在网络服务不是由API实现的方法,我需要注入这些代理方法动态。

There are methods in the web-services not implemented by the API, and I need to 'inject' these proxy methods dynamically.

所以我的问题是:?我如何添加方法到现有的类(而不是扩展方法)

So my question is: How can I add methods to an existing class (not extension methods)?

我能做到这一点, Reflection.Emit的,但我不知道MSIL。
反正我提到它,因为我做了另外一个类继承自同一个基类的API做,并实施有方法的,所以也许有一种方法来复制方法的API类,因为他们只调用哪个是指的同一个基类的方法

I could do this by Reflection.Emit, but I don't know MSIL.
Anyway I'm mentioning it, because I've made another class that inherits from the same base class as the API does, and implemented the methods there, so maybe there is a way to copy the methods to the API class, because they only call methods of the base class which refers to the same one.

推荐答案

实际上,有没有办法,你要修改现有的类在你想要的方式。即使使用Reflection.Emit的,它不会做你想做的,因为API调用是一个特定的类型,您可以在运行过程中不能修改一个类型的定义。您可对Reflection.Emit的做的就是定义一个类继承自代理,但得到的API来加载你的继承类型可能会证明,除非他们正在使用依赖注入框架,这似乎不太可能是不可能的。

Realistically, there's no way you're going to modify an existing class in the way you want. Even using Reflection.Emit, it won't do what you want because the API is calling a specific type, and you can't modify the definition of a type during runtime. What you can do with Reflection.Emit is define a type that inherits from the proxy, but getting the API to load your inherited type will probably prove to be impossible unless they're using a dependency injection framework, which seems unlikely.

唯一真正的方式做,这是去中和使用反编译和重新编译修改DLL的字节code。这是Postsharp怎么做AOP,但海事组织,我从来没有做任何其他原因。

The only real way to do this is to go in and modify the bytecode of the dll using decompilation and recompilation. This is how Postsharp does AOP, but imo, I'd never do this for any other reason.

如果您有任何访问该code,甚至他们的图书馆,那么有可能是在你的问题的一个更好的办法。

If you have any access to this code or even their libraries, then there is probably a better way around your problem.

这篇关于编程方法添加到类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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