Polymorphism and overloading with static methods in C#.

只愿长相守 提交于 2019-12-04 03:56:20

Overloading is decided at compile-time (aside from using dynamic typing in C# 4) based on the compile-time type of the arguments - and in your last snippet, the compile-time type of the argument is A, so it calls Factory.getItem(A).

Only virtual method calls are polymorphic (using overriding), where the actual execution-time type of the target object to decide which implementation to call. If it makes sense for A and B to have a virtual method (overridden in B) which can be called by Factory.getItem to handle the differences, that's great... otherwise you're stuck with either dynamic typing or something like is.

You can not achieve what you are pretending the way you have things set up right now.

One option is to have some logic in your factory methods that can distinguish the type of the argument. Clunky, not pretty, but it works:

class Factory
{
    static Item getItem(ContextA context)
    {
         if (context is ContextB) {...}
         else {...}
    }
}

Another option is to make the context objects responsible of creating the object. For example:

public class ContextA
{
     ....
     internal virtual Item CreateItem() { //specific creation logic for ContextA }
}

public class ContextB: ContextA
{
     ....
     internal override Item CreateItem() { //specific creation logic for ContextB }
}

And now you could do:

class Factory
{
    static Item getItem(ContextA context)
    {
         return context.CreateItem();
    }
}

No if you do the following:

 ContextA context = new ContextB();
 Item item = Factory.getItem(context)

ContextB.CreateItem() will be called.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!