gpt4 book ai didi

c# - 泛型方法 - 类型不能用作类型参数

转载 作者:太空宇宙 更新时间:2023-11-03 18:29:50 25 4
gpt4 key购买 nike

给定以下通用方法:

    /// <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>>'.

为什么会出现此错误以及如何更正我的代码?

最佳答案

这里有一个问题:

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) 

关于c# - 泛型方法 - 类型不能用作类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24874323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com