是否可以在运行时向EXISTING类添加一个方法?为什么或者为什么不? [英] Is it possible to add a method to an EXISTING class at runtime? why or why not?
问题描述
我想象这可能会使用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数据绑定。这就是 DataTable
表示列作为伪属性(暂时忘了打字数据集) -
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).
为了完整,我还应该提到扩展方法。那些更多的是一个编译器技巧,而不是一个运行时技巧 - 但是,您可以使用添加方法到现有类型 - 对于小的add值。
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".
ORMs等通常使用的最后一个技巧是动态子类,并在子类中提供附加功能。例如,覆盖属性以截取它们(延迟加载等)。
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).
这篇关于是否可以在运行时向EXISTING类添加一个方法?为什么或者为什么不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!