c# - 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)'
废话?
解决方案
问题是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)
推荐阅读
- typescript - Typescript 2 中是否需要分号?
- java - 无法将文本标记为横向 PDF
- size - SpiceJet.com 网站上的 Size() 方法给出的结果不正确
- ios - 如何在 iOS 中仅拖动图像视图的一个角
- reactjs - 使用 redux 的 react-native 应用程序中的状态问题
- c# - 代码优先实体框架中两种外键方法之间的区别
- javascript - 我可以在 Outlook javascript 中的 MessageComposeCommandSurface 中获取休息令牌吗?
- java - 解析json时字符串“jo”有什么问题?
- sql - 如何在条件下分隔逗号是数据集?
- ios - 快速同步多个 Web 服务调用以串行顺序