You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

复刻C#枚举器接口时是否需添加new关键字?

复刻C#枚举器接口的隐藏警告问题解析

为什么会出现警告?

你的泛型接口IMyEnumerator<T>和IMyEnumerable<T>中的成员,与非泛型基接口的同名成员(Current/GetEnumerator)签名不同但名称一致,编译器默认认为你可能是不小心隐藏了基接口成员,所以抛出警告提示你确认行为。

为什么VS F12看官方源码没看到new关键字?

VS的F12默认显示的是元数据视图,不是.NET的原始C#源码。实际上,.NET官方的IEnumerator<T>和IEnumerable<T>源码中,泛型接口的成员是明确使用了new关键字的,比如:

public interface IEnumerator<out T> : IDisposable, IEnumerator
{
    new T Current { get; }
}

new关键字在这里是编译时的语法提示,用于明确告知编译器:我们是故意隐藏基接口的同名成员,而非疏忽。这个关键字不会被编译到IL中,所以元数据里看不到。

正确的做法:添加new关键字

你应该按照警告提示添加new关键字,这不仅能消除警告,还能让代码意图更清晰,完全符合官方的设计规范。修改后的接口代码如下:

public interface IMyEnumerator {
    object Current { get; }
    bool MoveNext();
    void Reset();
}

public interface IMyEnumerator<out T> : IMyEnumerator, IDisposable {
    new T Current { get; }
}

public interface IMyEnumerable {
    IMyEnumerator GetEnumerator();
}

public interface IMyEnumerable<out T> : IMyEnumerable {
    new IMyEnumerator<T> GetEnumerator();
}

实现类的注意事项

对于MyContainer这类实现类,建议显式实现非泛型接口的GetEnumerator方法,避免调用时的歧义,同时复用泛型实现的逻辑:

public class MyContainer<T> : IMyEnumerable<T>, IMyEnumerable
{
    public IMyEnumerator<T> GetEnumerator()
    {
        // 这里实现泛型枚举器的逻辑
        throw new NotImplementedException();
    }

    // 显式实现非泛型接口
    IMyEnumerator IMyEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

内容的提问来源于stack exchange,提问作者kofifus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 19:27:34