【问题标题】:C# Auto-Casting Interface Methods [duplicate]C# 自动转换接口方法 [重复]
【发布时间】:2015-11-11 17:29:52
【问题描述】:

我有一个在其签名中使用抽象类的接口。然后我的实现在其签名中使用抽象类的子类,但这是不允许的。有人可以帮我吗?我在谷歌上只能找到通用接口和抽象类实现......

public MyAbstractClass {
    abstract public void myMethod();
}

public MySubClass : MyAbstractClass {
    override public void myMethod(){
        ...
    }
}

然后我有我的接口/实现..

public interface MyInterface {
    MyAbstractClass myInterfaceMethod(MyAbstractClass blah);
}

public MyImplementation : MyInterface {
    MySubClass myInterfaeMethod(MySubClass blah){
        ...
    }
}

但我在构建时收到错误消息,说 myInterfaceMethod 没有实现接口方法...

帮助?

【问题讨论】:

    标签: c# interface casting abstract


    【解决方案1】:

    您不能这样做,因为它违反了界面。但是,您可以将 MyInterface 设为通用。

    public interface MyInterface<T> where T: MyAbstractClass {
        T myInterfaceMethod(T blah);
    }
    
    public MyImplementation : MyInterface<MySubClass> {
        MySubClass myInterfaeMethod(MySubClass blah){
            ...
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 1970-01-01
      • 2017-02-06
      • 2017-12-04
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      相关资源
      最近更新 更多