且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

IEnumerable.GetEnumerator()和IEnumerable< T> .GetEnumerator()

更新时间:2021-07-30 14:56:16

之所以没有这样做,是因为它们将一个版本编译为显式接口方法实现.看起来像这样:

They don't because they compile one version as an Explicit Interface Method Implementation. It looks like this:

public class SomeClassThatIsIEnumerable<T> : IEnumerable<T>
{
    public IEnumerator<T> GetEnumerator()
    {
       // return enumerator.
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return ((IEnumerable<T>)this).GetEnumerator();
    }
}

这种构造类型的作用是使第一个GetEnumerator方法成为默认方法,而另一个GetEnumerator方法仅在调用者首先将SomeClassThatIsIEnumerable转换为IEnumerator类型时才可访问.

What this type of construct does is make the first GetEnumerator method become the default method, while the other GetEnumerator method is only accessible if the caller first casts SomeClassThatIsIEnumerable to the type IEnumerator, so it avoids the problem.

根据上面的补充,您想使用新关键字:

based on the supplement above, you would want to use the new keyword:

public interface IMyInterface
{
   object GetObject();
}

public interface IMyInterface<T> : IMyInterface
{
   new T GetObject();
}

// implementation:

public class MyClass : IMyInterface<string>
{
    public string GetObject() 
    {
        return "howdy!";
    }

    object IMyInterface.GetObject()
    {
        return GetObject();
    }
}