给出以下通用方法:
/// <summary>
/// Performs a MoveNext on the IEnumerator 'Enoomerator'.
/// If it hits the end of the enumerable list, it resets to the beginning.
/// </summary>
/// <returns>If False, MoveNext has failed even after resetting,
/// which means there are no entries in the list.</returns>
private static bool CyclicalSafeMoveNext<T>(T Enoomerator)
where T : IEnumerator<T>
{
if (Enoomerator.MoveNext()) // successfully moved to the next element
{
return true;
}
else
{
// Either reached last element (so reset to beginning) or
// trying to enumerate in a list with no entries
LogLine("CyclicalSafeMoveNext: failed a MoveNext, resetting.");
Enoomerator.Reset();
if (!Enoomerator.MoveNext())
{
// Still at end. Zero entries in the list?
LogLine("CyclicalSafeMoveNext: failed a MoveNext after
Reset(), which means there were no entries in the list.");
return false;
}
else
{
// Resetting was successful
return true;
}
}
}
编译此代码时
IEnumerator<FileInfo> FileInfoEnumerator files;
while (CyclicalSafeMoveNext(files))
{
return files.Current.FullName;
}
我收到错误:
Error 7 The type 'System.Collections.Generic.IEnumerator<System.IO.FileInfo>' cannot
be used as type parameter 'T' in the generic type or method
'CyclicalSafeMoveNext<T>(T)'. There is no implicit reference conversion from
'System.Collections.Generic.IEnumerator<System.IO.FileInfo>' to 'System.Collections.Generic.IEnumerator<System.Collections.Generic.IEnumerator<System.IO.FileInfo>>'.
为什么我收到此错误以及如何更正我的代码?
答案 0 :(得分:5)
这里有一个问题:
where T : IEnumerator<T>
您将通用类限制为类,它是自己的枚举器。
由于FileInfo
不是IEnumerator<FileInfo>
且IEnumerator<FileInfo>
不是IEnumerator<IEnumerator<FileInfo>>
,因此它失败了通用约束。
您可以添加第二种通用类型:
private static bool CyclicalSafeMoveNext<T, U>(T Enoomerator)
where T : IEnumerator<U>
或只是让IEnumerator<T>
成为签名的一部分:
private static bool CyclicalSafeMoveNext<T>(IEnumerator<T> Enoomerator)
答案 1 :(得分:2)
试
private static bool CyclicalSafeMoveNext<T>(IEnumerator<T> Enoomerator)
让where T : IEnumerator<T>
将其抛弃。