Common virtual methods - override method is ignored

I am trying to create a generic virtual method, but for some reason the override is ignored. A similar non-generic implementation works as expected.

Here is the basic code details:

EDIT: Turns out this might be more obscure than I expected - I use Unity / Mono and it doesn't work there, but it works in VS

EDIT: adding things to make it a complete program

public interface IController
{
    void Set<T>() where T : class, IController;
    void Set(Type t);
}

public abstract class Controller : IController
{
    public IController parent;
    public virtual void Set<T>() where T : class, IController
    {
        Console.WriteLine(GetType());
        parent.Set<T>();
    }
    public virtual void Set(Type t)
    {
        Console.WriteLine(GetType());
        parent.Set(t);
    }
}

public class ControllerGroup : Controller
{
    public override void Set<T>()
    {
        Console.WriteLine("Success!");
    }
    public override void Set(Type t)
    {
        Console.WriteLine("Success!");
    }
}

static class Program
{
    static void Main()
    {
        IController obj = new ControllerGroup();
        obj.Set<Controller>();
    }
}

EDIT / Clarification: the output should be "Success!". but instead "ControllerGroup", then of course the null reference exception

I access this method through an interface IControllerthat declares both of these methods. Not sure if it affects anything

, . , ControllerGroup, , , .

+4
1

. , Unity/Mono, , "callvirt" . , :

void IController.Set<T>()
{
    Set<T>();
}

this - , , .

0

Source: https://habr.com/ru/post/1538879/


All Articles