Why is this overridden method called?

public interface ITimeable     {}
public class TimedDoor : ITimeable  {}

public static class Timer
{
    public static void Add(ITimeable obj)
    {
       Console.Write("Add with parameter - ITimeable"); 
    }

    public static void Add(TimedDoor obj)
    {
       Console.Write("Add with parameter - TimedDoor"); 
    }
}

public class BaseClient<T> where T : ITimeable
{
    public T TimedDoorObject;
    public virtual void Init()
    {
        Timer.Add(TimedDoorObject);
    }
}

public class Client : BaseClient<TimedDoor>
{
    public Client()
    {
        TimedDoorObject = new TimedDoor();
    }

    public override void Init()
    {
        Timer.Add(TimedDoorObject);
    }
}

It Client.Init()returns"Add with parameter - TimedDoor"

But if the Client does not redefine Init (),

public class Client : BaseClient<TimedDoor>
{
    public Client()
    {
        TimedDoor = new TimedDoor();
    }
}

Client.Init()Returns here"Add with parameter - ITimeable"

How does this happen? TimedDoorObjectsame in both cases at runtime.

+4
source share
2 answers

If you add some explicit drops that represent what Trepresents at the point Timer.Add(TimedDoorObject), it is called more obvious what is happening.

public class BaseClient<T> where T : ITimeable
{
    public T TimedDoorObject;
    public virtual void Init()
    {
        Timer.Add((ITimeable)TimedDoorObject);
    }
}

public class Client : BaseClient<TimedDoor>
{
    public Client()
    {
        TimedDoorObject = new TimedDoor();
    }

    public override void Init()
    {
        Timer.Add((TimedDoor)TimedDoorObject);
    }
}

, BaseClient , , , T - - ITimeable, , , void Add(ITimeable obj). Client , T a TimedDoor, void Add(TimedDoor obj), , void Add(ITimeable obj).

+8

TimedDoorObject .

, , , , . , , ITimeable, td TimedDoor:

TimeDoor td = new TimedDoor();
Timer.Add((ITimeable)td);

TimedDoorObject ITimeable. Init TimedDoorObject , TimedDoor.

+4

All Articles