【问题标题】:implementing a generic interface that inherits from a non generic one实现从非通用接口继承的通用接口
【发布时间】:2016-03-03 14:26:14
【问题描述】:

我知道如何实现一个从非通用接口继承的通用接口,但是在这个过程中有一些我不明白的地方:

为什么非泛型接口方法不能在实现接口的类中声明为public?

一个例子:

    interface InputTestSocket
    {
        object GetValue();
    }

    interface InputTestSocket<T> : InputTestSocket
    {
        new T GetValue();
    }

    class FloatInputSocketValues : InputTestSocket<float>
    {
        IFloatConvertable _output;
        public void SetConvertable(IFloatConvertable output) { _output = output; }

        //If I make this method public it won't compile. Musn't all interfaces be public?
        object InputTestSocket.GetValue() { return null; }

        public float GetValue() { return _output.ToFloat(); }
    }

【问题讨论】:

    标签: c# generics


    【解决方案1】:

    这称为接口的显式实现。当您不会(或不能)将成员公开为具体类型上的实例成员时,您会这样做,而只能通过接口使它们可用。

    编译器报错的原因:

    CS0111 类型“FloatInputSocketValues”已经定义了一个名为“GetValue”的成员,具有相同的参数类型

    是您不能仅通过返回类型来区分两个成员,如果您将方法公开,您将拥有:

    //If I make this method public it won't compile. Musn't all interfaces be public?
    public object GetValue() { return null; }
    
    public float GetValue() { return _output.ToFloat(); }
    

    这两者的区别仅在于它们的返回类型。

    所以你不能这样做。

    您不能这样做的原因是,当编译器试图确定您在执行此操作时要调用哪个方法时:

    something.GetValue()
    

    是它根本不考虑返回类型。因此,编译器会告诉您,您永远无法调用此方法,因为它会模棱两可,因此它不允许您这样做。

    虽然这与泛型或继承无关,但您会在这个较小的示例中遇到完全相同的问题:

    interface ITest
    {
        object GetValue();
    }
    
    public class Test : ITest
    {
        public object GetValue() { return null; }
    
        // just a public method on our class
        public float GetValue() { return 0.0f; }
    }
    

    【讨论】:

    • 希望我可以为底部的歧义提供额外的 +1,特别是这不是泛型的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 2012-01-08
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    相关资源
    最近更新 更多