【问题标题】:Is it possible to explicitly implement base interfaces more than once?是否可以多次显式实现基本接口?
【发布时间】:2018-01-24 04:04:37
【问题描述】:

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

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
}

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

【问题讨论】:

  • 问题在于它会让最终用户感到困惑,为什么不改用 IConvertible 这样的范例呢?
  • 我已经意识到我的问题可能完全无效。在我的用例中,该类将被显式视为IEnumerable&lt;int&gt;IEnumerable&lt;double&gt;,而不是IEnumerable。由于方法名称相同,因此永远不应调用 IEnumerator.GetEnumerator(),而应抛出 InvalidOperationException 或类似名称。我需要再考虑一下。
  • 您的代码可能不会说,如果您使用 LINQ,它会在某个时候。顺便说一句,IEnumerator GetEnumerator 通常被实现为简单地返回专门重载的结果。 TL;DR 你必须实现这两个重载。
  • 当然可以。回到在IEnumerable&lt;T&gt;c# 4.0 中成为协变之前,您有时会看到实现IEnumerable&lt;T&gt;IEnumerable&lt;object&gt; 的类通常具有最多派生参数的泛型将直接实现,而具有基本参数的泛型将明确。 IEnumerable&lt;int&gt;IEnumerable&lt;double&gt; 会很奇怪——并且会混淆几乎所有的序列化程序。

标签: c#


【解决方案1】:

我不确定这是否可能,但我认为这是一种代码味道。正如您所说的那样,唯一可行的情况是-为泛型类实现特定版本时。在这种情况下,您应该利用类型变量,而不是现在如何获得它。

【讨论】:

    【解决方案2】:

    因此,您可以将其提高到可以编译代码的程度。从 IEnumerable 接口你必须实现GetEnumerator(),但你必须决定是返回intList 还是doubleListIEnumerable&lt;int&gt;IEnumerable&lt;double&gt;GetEnumerator() 上具有相同的签名,因此无法同时实现它们,因为编译器会报错。

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

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

    【讨论】:

      猜你喜欢
      • 2018-02-08
      • 2017-12-26
      • 2021-11-20
      • 2015-02-23
      • 2014-03-26
      • 2015-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多