简体   繁体   中英

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. How to fix class C , so that fun(B b) is invoked when b 's runtime type is B , but compilation type is A ? Currently it works properly only when I declare b as B during compilation.

@Edit: without checking types with if s etc.

Invoke fun via a virtual method.

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:

that was A
that was B

See example on Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM