接口作为参数的基类虚方法不能被实现覆盖

时间:2017-07-20 15:46:00

标签: c# interface virtual

我有一个定义

的基类
public class BaseClass 
{
    public virtual bool StartUpdate( Interface )
    { some code here }
}

然后,有一个实现接口

的类
public ClientClass : Interface {}

在派生类

public class DerivedClass : BaseClass
{
    public override bool StartUpdate( ClientClass )
    { some code... }
} 

编译器(c#)在DerivedClass上引发错误,告知没有找到合适的覆盖方法。 我做错了什么?为什么编译器不能注意ClientClass实现Interface

任何帮助将不胜感激。

编辑:

找到“解决方案”

在基类

public virtual bool StartUpdate( object o )
{
    checkInterface( o ); // if not o is Interface, throws an exception
    more code...
}

在派生类

public override bool StartUpdate( object o )
{
    // o will always implement Interface 
}

这是一团糟,但c#喜欢它的方式。

3 个答案:

答案 0 :(得分:1)

您的基类方法签名是:

public virtual bool StartUpdate(Interface obj) { }

但在您的派生类中,您写道:

public override bool StartUpdate(ClientClass obj) { }

即使ClientClass实现Interface,它也不是同一类型。派生的方法签名应该是Interface。来自MSDN中的规范:

  

重写的基本方法必须与覆盖方法

具有相同的签名

如果您希望派生方法具有不同的具体类型,请考虑generics

public class BaseClass<T> where T : Interface 
{
    public virtual bool StartUpdate(T data) { /*code here*/ }
}

public class Derived : BaseClass<ClientClass> 
{
    public override bool StartUpdate(ClientClass data) { /*code here*/ }
}

答案 1 :(得分:1)

这可能是您正在寻找的:

public class BaseClass<T> where T: Interface
{
    public virtual bool StartUpdate(T input)
    {
        // return whatever
    }
}

public class DerivedClass : BaseClass<ClientClass>
{
    public override bool StartUpdate(ClientClass input )
    {
        // return whatever
    }
} 

答案 2 :(得分:0)

在减少覆盖方法的范围时,无法覆盖方法。您必须接受所有类型的接口,否则您将减少基类的功能,这是不允许的。所以你应该写:

public override bool StartUpdate( Interface obj )

这称为Liskov substition principle

相关问题