I have a class that is generated by some tool, therefore I can't change it. The generated class is very simple (no interface, no virtual methods):
class GeneratedFoo
{
public void Write(string p) { /* do something */ }
}
In the C# project, we want to provide a way so that we can plug in a different implementation of MyFoo. So I'm thinking to make MyFoo derived from GeneratedFoo
class MyFoo : GeneratedFoo
{
public new void Write(string p) { /* do different things */ }
}
Then I have a CreateFoo method that will either return an instance of GeneratedFoo or MyFoo class. However it always calls the method in GeneratedFoo.
GeneratedFoo foo = CreateFoo(); // if this returns MyFoo,
foo.Write("1"); // it stills calls GeneratedFoo.Write
This is expceted since it is not a virtual method. But I'm wondering if there is a way (a hack maybe) to make it call the derived method.
Thanks,
Ian
Adam gave you an answer (correct one). Now it's time for hack you were asking for :)
class BaseFoo
{
public void Write() { Console.WriteLine("Hello simple world"); }
}
class DerFoo : BaseFoo
{
public void Write() { Console.WriteLine("Hello complicated world"); }
}
public static void Main()
{
BaseFoo bs = new DerFoo();
bs.Write();
bs.GetType().GetMethod("Write").Invoke(bs, null);
}
Prints out:
Hello simple world Hello complicated world
Without being able to make the method virtual, no. A non-virtual method is statically linked at compile time and can't be changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With