首页 > 解决方案 > C# 泛型错误,抱怨它不能在相同的元组类型之间转换

问题描述

尝试做我自己的 zip,得到了这个代码(泛型参数 T 定义在这个方法的封闭类上)。

public List<(T, T2)> Zip<T, T2>(SQLList<T2> that)
            where T2 : LDBSQLemitter {
    var res = this.Zip(that).ToList();
    return res;
}

错误是

错误 CS0029 无法将类型 'System.Collections.Generic.List<(T First, T2 Second)>' 隐式转换为 'System.Collections.Generic.List<(T, T2)>'

'System.Collections.Generic.List<(T First, T2 Second)>' 中的 First/Second 是什么,为什么在 'System.Collections.Generic.List<(T, T2)>' 中缺少它 - - 什么是关于我在这里不理解的元组类型吗?

好的,改用 try 对每个元组进行显式转换,所以

public List<(T, T2)> Zip<T, T2>(SQLList<T2> that)
                where T2 : LDBSQLemitter {
        var tmp = this.Zip(that).ToList();
    
        var res = new List<(T, T2)>();
        foreach (var x in tmp) {
            res.Add((x.First, x.Second));
        }
    
        return res;
    }

现在错误完全令人困惑,显然抱怨它无法在 2 个相同的元组类型之间进行转换:

错误 CS1503 参数 1:无法从 '(T, T2)' 转换为 '(T, T2)'

废话?

标签: c#generics

解决方案


问题是this,编译器无法与之相关T

了解班级的签名也将有所帮助。它还包含通用参数T吗?T通过在您定义了两次的方法中也有一个通用参数T,它们并不相同。

您可以通过显式转换来修复它

var res = ((IEnumerable<T>)this).Zip(that).ToList();

或添加演员

var res = this.Cast<T>().Zip(that).ToList();

或者去掉方法中多余的 T

public List<(T, T2)> Zip<T2>(SQLList<T2> that)


推荐阅读