Without inherit but only with reflection is it possible to dynamically change the code of a method in C#?
something like :
nameSpaceA.Foo.method1 = aDelegate;
I cannot change/edit The Foo Class.
namespace nameSpaceA
{
class Foo
{
private void method1()
{
// ... some Code
}
}
}
My final objective is to change dynamicaly the code of :
public static IList<XPathNavigator> EnsureNodeSet(IList<XPathItem> listItems);
In System.Xml.Xsl.Runtime.XslConvert.cs
to turn :
if (!item.IsNode)
throw new XslTransformException(Res.XPath_NodeSetExpected, string.Empty);
into :
if (!item.IsNode)
throw new XslTransformException(Res.XPath_NodeSetExpected, item.value);
The first part of this answer is wrong, I’m only leaving it so that the evolution in the comments makes sense. Please see the EDIT(s).
You’re not looking for reflection, but emission (which is the other way around).
In particular, there’s a method that does just what you want, lucky you!
See TypeBuilder.DefineMethodOverride
EDIT:
Writing this answer, I just remembered that re-mix allows you to do this too. It’s way harder though.
Re-mix is a framework that “simulates” mixins in C#. In its basic aspect, you can think of it as interfaces with default implementations. If you go further, it becomes much more than that.
EDIT 2: Here is an example of use for re-mix (implementing INotifyPropertyChanged on a class that doesn’t support it, and has no idea of mixins).
And the test:
Please note that:
and
and
Have the exact same effect. It is a matter of where you wish to define that a particular mixin is applied to a particular class.
Example 2: overriding Equals and GetHashCode
That example is my implementation of the hands-on lab given with re-mix. You can find more information there.