我经常必须实现一些接口,例如 IEnumerable<T> 在我的代码中。

每次自动实施时,我都会遇到以下内容:

public IEnumerator<T> GetEnumerator() {
    // Code here...
}

public IEnumerator GetEnumerator1() {
    // Code here...
}

虽然我必须同时实施 getEnumerator() 方法,即使我们知道它们也以某种方式也可以拥有相同的名称。编译器不能将它们视为另一个的过载,因为只有返回类型有所不同。

这样做时,我设法设置 GetEnumerator1() 登记器 private. 。这样,编译器不会抱怨不实施接口成员,我只是扔了一个 NotImplementedException 在该方法的身体中。

但是,我想知道这是一个好习惯,还是我会以不同的方式进行,也许是一种别名或类似的方法。

实施界面时最好的方法是什么 IEnumerable<T> 这需要实现两种具有相同名称的不同方法?

编辑#1

VB.NET在实现接口时与C#有不同的反应,因为在VB.NET中,它是明确实现的,因此强迫 GetEnumerator1(). 。这是代码:

Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of T) Implements System.Collections.Generic.IEnumerable(Of T).GetEnumerator
    // Code here...
End Function

Public Function GetEnumerator1() As System.Collections.Generic.IEnumerator Implements System.Collections.Generic.IEnumerable.GetEnumerator
    // Code here...
End Function

两个都 GetEnumerator() 方法是明确实施的,并且编译将拒绝它们具有相同的名称。为什么?

有帮助吗?

解决方案

在Visual Basic中, 所有接口实现都是明确的.

接口映射由 Implements 语句因此,您可以随心所欲地命名接口实现方法。 (与C#不同,在其中编译器通过匹配其名称和签名来实现接口的编译器。)

更改方法名称和可见性(毫无疑问)是VB中的标准实践。看 在vb.net中实现接口 为了进行良好的概述。

其他提示

您可以使用 显式接口实现:

IEnumerator IEnumerable.GetEnumerator()
{
    return GetEnumerator();
}

public IEnumerator<T> GetEnumerator()
{
    ...
}

你应该能够使用 显式接口实现 创建具有相同签名的两种方法。根据您的枚举,我只会将这些调用传递给内部 IEnumerable<T> 例如列表或数组。

显式实现非类别接口允许这两种方法具有相同的名称,并允许通过通用词来实现非传播版本。沿着:

public class TestEnumerable : IEnumerable<int>
{
    public IEnumerator<int> GetEnumerator()
    {
        // Type-safe implementation here.
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top