[英]Generic method - Type cannot be used as Type Parameter
Given the following Generic Method: 给定以下通用方法:
/// <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;
}
}
}
When I compile this code 当我编译这段代码
IEnumerator<FileInfo> FileInfoEnumerator files;
while (CyclicalSafeMoveNext(files))
{
return files.Current.FullName;
}
I get the error: 我得到错误:
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>>'.
Why am I getting this error and how do I correct my code? 为什么会出现此错误,以及如何更正我的代码?
One problem is here: 一个问题在这里:
where T : IEnumerator<T>
You're restricting the generic class to a class that is its own enumerator . 您将泛型类限制为自己的枚举器类 。
Since FileInfo
is not an IEnumerator<FileInfo>
and IEnumerator<FileInfo>
is not an IEnumerator<IEnumerator<FileInfo>>
it fails the generic constraint. 由于FileInfo
不是IEnumerator<FileInfo>
并且IEnumerator<FileInfo>
不是IEnumerator<IEnumerator<FileInfo>>
因此它无法通过通用约束。
You could add a second generic type: 您可以添加第二个泛型类型:
private static bool CyclicalSafeMoveNext<T, U>(T Enoomerator)
where T : IEnumerator<U>
or just make IEnumerator<T>
part of the signature: 或者只是将IEnumerator<T>
设置为签名的一部分:
private static bool CyclicalSafeMoveNext<T>(IEnumerator<T> Enoomerator)
try 尝试
private static bool CyclicalSafeMoveNext<T>(IEnumerator<T> Enoomerator)
having the where T : IEnumerator<T>
is throwing it off. 具有where T : IEnumerator<T>
正在抛出它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.