[英]Sending base class to a method which receives derived class - c#
I have a Base class and 2 derived classes. 我有一个基类和2个派生类。 I have a variable of base class which can hold one of the derived classes.
我有一个基类的变量,可以容纳其中一个派生类。 I want to send that variable to a method which receives derived classes.
我想将该变量发送到接收派生类的方法。
What can I do to resolve this problem without explicit cast since I don't know what the variable holds? 由于不知道变量包含什么,该如何解决而无需显式强制转换?
code: 码:
Class A{
virtual public void foo1() {/.../}
}
Class B : A{
override public void foo1() {/.../}
}
Class C : A{
override public void foo1() {/.../}
}
Class D{
public foo(B argB) {/.../}
public foo(C argC) {/.../}
// in main
D varD = new D();
A varA = new B();
varD.foo(varA); //--->> Problem here need explicit casting
A varC = new C();
varD.foo(varC); //--->> Problem here need explicit casting
I don't know what derived class I'm sending to varD.foo
and I want different handling of different derived classes. 我不知道我要向
varD.foo
发送什么派生类,并且我想对不同派生类进行不同的处理。 What can I do? 我能做什么?
This is not what polymorphism is about - you can not pass a base class where a specialized class is expected, even when explicitly casting. 这不是多态性的意思-即使在显式转换时,也不能传递需要专门类的基类。 Polymorphism works the other way: You can pass a specialized class wherever the base class is expected.
多态性以另一种方式起作用:您可以在需要基类的任何地方传递专门的类。
What you should do is make D.foo
expect A
and you will automatically be fine. 您应该做的是使
D.foo
期望A
然后您会自动好起来的。 If you add any methods to B
or C
which have no base implementation in A
, you need to pass B
anyway and can not cast an A
to B
or D
. 如果向
B
或C
添加任何在A
没有基本实现A
,则无论如何都需要传递B
,并且不能将A
为B
或D
Just make foo
an abstract instance method of A
and override the implementation in B
and C
. 只需将
foo
作为A
的抽象实例方法,并覆盖B
和C
的实现即可。 You could even keep your class D
and delegate the actual work to there but it depends if this is a good idea. 您甚至可以保留
D
类并将实际工作委托在那里,但这取决于这是否是一个好主意。
Here the code with delegation to D
. 这里的代码带有委托给
D
。 Also note that I omitted the method foo1()
in all classes. 还要注意,我在所有类中都省略了
foo1()
方法。
public abstract class A
{
public abstract void foo(D d);
}
public sealed class B : A
{
public override void foo(D d)
{
d.foo(this);
}
}
public sealed class C : A
{
public override void foo(D d)
{
d.foo(this);
}
}
public sealed class D
{
public void foo(B b) { [...] }
public void foo(C c) { [...] }
}
Now you can use virtual method dispatching to call the correct method. 现在,您可以使用虚拟方法分派来调用正确的方法。
D d = new D();
A b = new B();
A c = new C();
b.foo(d); // Calls B.foo(D) and in turn D.foo(B).
c.foo(d); // Calls C.foo(D) and in turn D.foo(C).
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.