指定的Cast无效-IEnumerable到T,其中T:IEnumerable

时间:2019-10-24 17:21:45

标签: string generics casting ienumerable

我正在为所编写的泛型方法获取InvalidCastException。我想做的是将IEnumerable <字符串>强制转换为T,这是IEnumerable <字符串>。经过更多阅读后,它可能是不可能的,但是如果有人可以确认,我将不胜感激。

这是我的代码:

public static T ToIdentifiers<T>(this T enumerable, string enclosingType, bool allowDuplicates) where T : IEnumerable<string>
{
    enumerable = (T)enumerable.Select(it => it.ToIdentifier(enclosingType));

    if(allowDuplicates)
        return enumerable;

    List<string> uniqueIdentifiers = new List<string>();
    using(var enumerator = enumerable.GetEnumerator())
    {
        while(enumerator.MoveNext())
        {
            int? index = null;

            while(uniqueIdentifiers.Contains(enumerator.Current + index))
                index++;

            uniqueIdentifiers.Add(enumerator.Current + index);
        }
    }

    return (T)uniqueIdentifiers.AsEnumerable();
}

在理想情况下,这将允许new string[]{}.ToIdentifiers()返回字符串[]和new List<string>().ToIdentifiers()返回List ,但是我想我现在理解为什么Linq尚未这样做

0 个答案:

没有答案