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

时间:2014-07-21 20:40:44

标签: c# generics

给出以下通用方法:

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

为什么我收到此错误以及如何更正我的代码?

2 个答案:

答案 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>将其抛弃。