I'm writing a game server in C# and now I have a problem of calling appropriate method handling each message by its type correctly. My current solution illustrated in this simple code:
public class DynamicBase
{
public int Method(Abc abc) => 2;
public virtual void Run()
{
IAbc abc = new Abc();
Console.WriteLine(Method((dynamic)abc)); // print 2
IAbc aha = new Aha();
// expecting print 3
Console.WriteLine(Method((dynamic)aha)); //Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
}
}
public class DynamicSub : DynamicBase
{
public int Method(Aha a) => 3;
}
public class Abc : IAbc { }
public class Aha : IAbc { }
public interface IAbc { }
//In Main(): new DynamicSub().Run();
The exception for Method((dynamic)aha)
is due to the runtime only check for Method
overloads of DynamicBase
and its base class. If I want it to call Method
in DynamicSub
then I need to override the Run
with exact the same code in base class.
So, how can I achieve this behavior without an override?
If not, how can I dynamically emit an override of Run
for the sub class by programmatically copying the virtual method (I mean IL code)? So that my user (of my lib) doesn't have to copy the Run
method to sub class by herself.