接口继承和重载

Interface Inheritence & Overloads

我正在处理一个接口如下:

public interface ISomething
{
    ...many auto-props, 
    void SetValues(ISomething thing) 
}

现在,我不拥有此接口,但我想用更多属性扩展它:

public interface ISomethingMoreSpecific : ISomething
{ 
    ...existing + my props, 
    void SetValues(ISomething thing)
}

在 class 实现中 ISomethingMoreSpecific 我已经实现了一个重载,它采用派生接口并处理我的道具和基本接口属性。

public void SetValues(ISomethingMoreSpecific specificThing) 
{
    ...set my props and base props
}

调用代码执行以下操作:

myThing.SetValues((ISomethingMoreSpecific)otherThing);

有或没有强制转换,即使 otherThingmyThing 是实现 ISomethingMoreSpecific 的具体类型,该方法也不会分派到我的重载。我猜我忽略了一些简单的东西,但它是什么?

包括

void SetValues(ISomethingMoreSpecific specificThing);

进入 ISomethingMoreSpecific。

您在 ISomethingMoreSpecific 中再次获得 void SetValues(ISomething thing)。你打算隐藏它,然后使用 new 关键字。如果你不想隐藏,你需要在 ISomethingMoreSpecific 中将 void SetValues(ISomething thing) 更改为 void SetValues(ISomethingMoreSpecific)。以下是您打算隐藏时的代码,它确实适用于转换。即使您不隐藏它,即不使用 new 关键字。它有效。

public class Program
{
    public void Main(string[] args)
    {
        MyThing a = new MyThing();
        MyThing b = new MyThing();
        a.SetValues(b);//calls more specific
        a.SetValues((ISomething)b);//calls just the thing
    }   
}


public class MyThing : ISomethingMoreSpecific
{
    public void SetValues(ISomethingMoreSpecific specificThing)
    {
        Console.WriteLine ("more specific");
    }

    public void SetValues(ISomething thing)
    {
        Console.WriteLine ("just the thing");
    }
}

public interface ISomethingMoreSpecific : ISomething
{ 
    //...existing + my props, 
    new void SetValues(ISomething thing);
}

public interface ISomething
{
    //...many auto-props, 
    void SetValues(ISomething thing) ;
}