我正在收集,實施IEnumerable
明確,並試圖從內重複它:警告 - 未實現「集合」模式
public class MyCollection<T> : IEnumerable<T>, IEnumerable
{
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
IEnumerator<T> GetEnumerator() { yield return default(T); } // test
public void Test()
{
foreach (var item in this) { } // here is warning
}
}
我收到編譯器警告在this
:
警告CS0279'MyCollection'沒有實現'collection'模式。 'MyCollection.GetEnumerator()'是靜態的或不公開的。
地獄是的,它不公開。爲什麼它應該是?我可以將其公開,但它不需要foreach
類型之外:
foreach (var item in new MyCollection<string>()) { } // no warning
難道我做錯了什麼?
叫它別的東西嗎? 'GetEnumeratorImpl'?或者只是不使用顯式接口實現'IEnumerable .GetEnumerator?' –
@JonSkeet,所以它只是名稱編譯器? – Sinatr
是的 - 因爲'foreach' *中的模式匹配找到* GetEnumerator()'方法,但不能使用它。現在添加一個答案... –