是否有可能的方法在运行时添加到现有的类?为什么或者为什么不? [英] Is it possible to add a method to an EXISTING class at runtime? why or why not?

查看:81
本文介绍了是否有可能的方法在运行时添加到现有的类?为什么或者为什么不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我猜想这可能使用Reflection.Emit的,

I would imagine this might use Reflection.Emit,

不过的 SO上只回答如何动态地创建一个类/方法,而不是如何更新现有类类似的问题。

but a similar question on SO only answers how to create a class/method dynamically, not how to update an existing class.

在此类似,是有可能在运行时删除方法/类?如果是这样,我想人们可以只删除类,并与它的老方法,再加上新添加回去。

In a similar vein, is it possible to delete methods / classes at runtime? If so, I suppose one could just delete the class, and add it back with its old methods plus the new one.

在此先感谢。

PS我没有一个这样的用途,它仅仅是好奇的问题。

P.S. I don't have an intended use for this, it is merely a matter of curiosity.

推荐答案

在常规的C#/。NET ,答案是一个简单的不。你能做的最重要的是写一个 DynamicMethod的这可以表现得这样的类型(访问私有字段等)的方法,但它赢得了 ŧ永远是对的API - 你刚刚结束了一个代表

In regular C# / .NET, the answer is a simple "no". The most you can do is write a DynamicMethod which can behave like a method of that type (access to private fields etc), but it won't ever be on the API - you just end up with a delegate.

如果您使用动态,你可以你所需的内容。你可以模仿与 ExpandoObject 通过附加的代表的代替方法,但在自定义动态类型,你可以做任何东西 - 但这只是影响谁使用动态 API调用者。对于基本 ExpandoObject 例如:

If you use dynamic, you can do pretty much anything you want. You can emulate that with ExpandoObject by attaching delegates in place of methods, but on a custom dynamic type you can do most anything - but this only impacts callers who use the dynamic API. For a basic ExpandoObject example:

dynamic obj = new ExpandoObject();
Func<int, int> func = x => 2*x;
obj.Foo = func;
int i = obj.Foo(123); // now you see it
obj.Foo = null; // now you don't

有关的属性和事件的(而不是方法),你可以使用 System.ComponentModel 办法改变在运行时显示的内容,但只影响呼叫者通过谁 System.ComponentModel ,这主要是指:UI数据绑定。这是数据表如何代表假性性柱(忘记了类型化数据集的时刻 - 它的作品没有这些)

For properties and events (not methods), you can use the System.ComponentModel approach to change what appears at runtime, but that only impacts callers who get access via System.ComponentModel, which means mainly: UI data-binding. This is how DataTable represents columns as pseudo-properties (forgetting about "typed datasets" for the moment - it works without those).

有关完整性,我还要提到的扩展方法的。这些更多的是编译器的把戏,而不是运行绝招 - 不过的还挺的让你的方法添加到现有的类型 - 为增加小值

For completeness, I should also mention extension methods. Those are more a compiler trick, not a runtime trick - but kinda allow you to add methods to an existing type - for small values of "add".

最后一个绝招,通过奥姆斯等常用的 - 是动态的子类的类型,并在子类中提供附加功能。例如,覆盖性能去拦截(延迟加载等)。

One final trick, commonly used by ORMs etc - is to dynamically subclass the type, and provide additional functionality in the subclass. For example, overriding properties to intercept them (lazy-loading, etc).

这篇关于是否有可能的方法在运行时添加到现有的类?为什么或者为什么不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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