是否可以多次显式实现基接口?

时间:2018-01-24 04:04:38

标签: c#

如果我们有两个具有类必须实现的公共基础的接口,是否可以显式实现公共基础?

例如考虑IEnumerable<T>

public class MyMultiEnumerable: IEnumerable<int>, IEnumerable<double>
{
    private readonly List<int> intList = new List<int>();
    private readonly List<double> doubleList = new List<double>();

    IEnumerator<double> IEnumerable<double>.GetEnumerator()
    {
        return doubleList.GetEnumerator();
    }
    IEnumerator<int> IEnumerable<int>.GetEnumerator()
    {
        return intList.GetEnumerator();
    }

    public IEnumerator GetEnumerator()
    {
        /*
         * How do we deal with this common case, where in context it means
         * two different things?
         */
        throw new System.NotImplementedException();
    }
}

我没有要求这样做,但我从理论角度感兴趣。

更新#1

我认为我对IEnumerable和基本类型的使用正在混淆这一点,在考虑了它之后,我相信它可以被剥夺回到这个问题:

public interface CommonBase
{
    void CommonMethod();
}

public interface AltBase1 : CommonBase
{
    void UnommonMethod();
}

public interface AltBase2 : CommonBase
{
    void UnommonMethod();
}

public class Example : AltBase1, AltBase2
{
    public void CommonMethod()
    {
        /*
         * If this method needs to know whether it is being called on behalf
         * of AltBase1 or AltBase2, how could it determine the implementation?
         */
    }

    void AltBase2.UnommonMethod()
    {

    }

    void AltBase1.UnommonMethod()
    {

    }
}

因为似乎无法显式实现接口的继承成员(下面的示例如下所示)。我坚信通过任何传统方法都无法做到这一点,因为它似乎是一个多重继承问题。

void AltBase1.CommonBase.CommonMethod()
{
    // AltBase1 targeted Implementation
}

是否可以通过任何基于Meta的方法实现,或者根本不实现?

2 个答案:

答案 0 :(得分:0)

我不确定它是否可行,但我认为这是一种代码味道。在实现泛型类的特定版本时,唯一可行的情况就是您已经表达过它。在那种情况下,你应该利用类型变量,而不是你现在如何得到它。

答案 1 :(得分:0)

因此,您可以将其设置为可以编译代码的位置。从IEnumerable接口,您必须实现GetEnumerator(),但您必须决定是否要返回intListdoubleListIEnumerable<int>IEnumerable<double>都在GetEnumerator()上具有相同的签名,因此编译器会抱怨,因此无法实现它们。

看一下这篇文章,因为它有很好的兼容/不兼容的例子,说明如何使用相同的方法处理接口。

Implementing two interfaces in a class with same method. Which interface method is overridden?