I wonder if it would be possible to insert classes in an inheritance tree at arbitrary positions.
Example:
class Base
{
public virtual void DoSomething()
{
Console.WriteLine("Base");
}
}
class D1:Base
{
public override void DoSomething()
{
base.DoSomething();
Console.WriteLine("D1");
}
}
class D2:Base
{
public override void DoSomething()
{
base.DoSomething();
Console.WriteLine("D2");
}
}
class D3:Base
{
public over开发者_Go百科ride void DoSomething()
{
base.DoSomething();
Console.WriteLine("D3");
}
}
Imagine the above classes are from a library with no source available. If I want to modify the behaviour of all the derived classes I have to inherit from all of them and implement the same thing multiple times. Then I have to change all types to my newly derived one. An easier way would be to insert a class directly after Base and somehow (that is probably a big somehow) make the derived class point to that as their base object. The derived classes could then be used unchanged.
class Inserted : after Base
{
public override void DoSomething()
{
base.DoSomething();
Console.WriteLine("Inserted");
}
}
or
class Inserted : before D1
{
public override void DoSomething()
{
base.DoSomething();
Console.WriteLine("Inserted");
}
}
The keywords "before" and "after" would control where exactly the class is to be inserted.
In the past I worked with a system that would support something like this and it was a huge productivity boost.
Is this principially possible with for instance, the .Net CLR or with the Java Runtime? Would it be possible to change the v_table to point to the new base class? Why does no modern system support this? What would the ramifications be regarding reliability, security and so on?
The guys from JRebel are unable to deal with changes in the type hierarchy on the JVM and since it is their core competency I conclude it is very near impossible.
However I think that most things you would like to do can be done using Aspect Oriented Programming and AspectJ.
Are you looking for the decorator pattern when you say "modifying behaviour"?
This can not be done in .NET and Java. Can you tell what system supports that?
精彩评论