Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

c# - Is it possible to add a method to an EXISTING class at runtime? why or why not?

I would imagine this might use Reflection.Emit,

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.

Thanks in advance.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...