如何继承方法但具有不同的返回类型? [英] How to Inherit method but with different return type?
问题描述
给出以下类:
ClassA
{
public ClassA DoSomethingAndReturnNewObject()
{}
}
ClassB : ClassA
{}
ClassC : ClassA
{}
有没有办法获得 ClassB
和 ClassC
继承方法但是将返回类型自定义为自己的类?
Is there a way to get ClassB
and ClassC
to inherit the method but customize the return type to their own class?
我不想从ClassA复制方法并在那里更改类型。
I prefer not to copy the method from ClassA and change the type there.
当我调用 ClassB.DoSomethingAndReturnNewObject()时,我需要得到一个
ClassB
对象/ code>。
I need to get a ClassB
object when I call ClassB.DoSomethingAndReturnNewObject()
.
当我打电话给 ClassC
对象> ClassC.DoSomethingAndReturnNewObject()。
I need to get a ClassC
object when I call ClassC.DoSomethingAndReturnNewObject()
.
类似于根据当前类型调用构造函数,如: this.GetType( )
?但我不知道如何实际做到这一点。
Something like calling a constructor based on current type like: this.GetType()
? But I have no clue how to actually do that.
推荐答案
您需要为<$ c $创建受保护的虚拟方法c> DoSomethingAndReturnNewObject 使用:
class ClassA
{
protected virtual ClassA Create()
{
return new ClassA()
}
public ClassA DoSomethingAndReturnNewObject()
{
ClassA result = Create();
// Do stuff to result
return result;
}
}
class ClassB : ClassA
{
protected override ClassA Create() { return new ClassB(); }
}
class ClassC : ClassA
{
protected override ClassA Create() { return new ClassC(); }
}
注意返回类型仍为ClassA,但对象实例类型将是特定的class。
Note the return type remains ClassA but the object instance type will be the specific class.
这篇关于如何继承方法但具有不同的返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!