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

本文关键字:类型参数 不能 类型 泛型方法 | 更新日期: 2023-09-27 18:13:52

给定以下通用方法:

    /// <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) 

try

private static bool CyclicalSafeMoveNext<T>(IEnumerator<T> Enoomerator)

拥有where T : IEnumerator<T>是把它扔掉。