C#中的多态和使用静态方法的重载. [英] Polymorphism and overloading with static methods in C#.
问题描述
我一直在尝试生成一个工厂,该工厂应该根据函数getItem(A context)
的输入参数(我称其为上下文)返回通用接口的另一个对象(例如Item
)
I have been trying to generate a Factory supposed to return a different object of a common interface (say Item
) according to the input parameter (I call it a context) of the function getItem(A context)
现在,假设我定义了一种新的上下文类型:B
,它是从A
继承的.
Now, assume I define a new type of context: B
which inherits from A
.
我想根据传递给工厂的对象是B
还是A
类返回不同的项目.
I wanted to return a different item depending on whether the object passed to the factory was of class B
or A
.
我尝试执行以下操作(重载方法):
I tried to do as follows (overloading the method):
class Factory
{
static Item getItem(A context) {...}
static Item getItem(B context) {...}
}
如果我做这样的事情,这会很好:
This works fine if I do something like this:
B bContext=new B();
Item it=Factory.getItem(bContext);
但是,如果我强制并拒绝键入A
:
However, if I cast and object to type A
:
A bContext=(A) new B();
Item it=Factory.getItem(bContext);
第一个工厂方法被调用.
the first factory method is called.
我认为即使在强制转换之后,多态性也可以确保第二种方法的执行,我想知道是否错过了什么吗?
I thought that polymorphism would ensure the execution of the second method even after the cast, and I would like to know if I missed something?
我知道我可以继续使用一个方法,并使用is
运算符检查变量的类型,但是我认为我上面介绍的解决方案更加优雅.
I am aware that I could keep having a single method and use the is
operator to check what the type of the variable is, but I thought the solution I presented above was a bit more elegant.
推荐答案
重载是根据编译时(除了在C#4中使用动态类型)决定的,参数-在您的最后一个代码段中,参数的编译时类型为A
,因此调用了Factory.getItem(A)
.
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)
.
只有虚拟方法调用是多态的(使用 overriding ),在此方法中,目标对象的实际执行时间类型决定了要调用的实现.如果A
和B
拥有一个虚拟方法(在B
中重写)是有意义的,可以由Factory.getItem
调用该方法来处理差异,那就太好了...否则,您将无法使用任何动态方法或类似is
的输入.
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
.
这篇关于C#中的多态和使用静态方法的重载.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!