[英]overloading with runtime type in c#
Consider following code:考虑以下代码:
public class A
{
public A(){}
}
public class B:A
{
public B(){}
}
public class C
{
public C(){}
public void fun(A a)
{
Console.WriteLine("that was A");
}
public void fun(B b)
{
Console.WriteLine("that was B");
}
}
public class Program
{
public static void Main()
{
A a = new A(), b = new B();
C c = new C();
c.fun(a);
c.fun(b);
}
}
In the current form, it says "that was A"
twice.在当前形式中,它说
"that was A"
两次。 How to fix class C
, so that fun(B b)
is invoked when b
's runtime type is B
, but compilation type is A
?如何修复 class
C
,以便在b
的运行时类型为B
时调用fun(B b)
,但编译类型为A
? Currently it works properly only when I declare b
as B
during compilation.目前它只有在我在编译期间将
b
声明为B
时才能正常工作。
@Edit: without checking types with if
s etc. @Edit:不使用
if
等检查类型。
Invoke fun
via a virtual method.通过虚拟方法调用
fun
。
public class A
{
public virtual void fun(C c)
{
c.fun(this);
}
}
public class B:A
{
public override void fun(C c)
{
c.fun(this);
}
}
public class C
{
public void fun(A a)
{
Console.WriteLine("that was A");
}
public void fun(B b)
{
Console.WriteLine("that was B");
}
}
public class Program
{
public static void Main()
{
A a = new A(), b = new B();
C c = new C();
a.fun(c);
b.fun(c);
}
}
Output: Output:
that was A
that was B
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.