提问人:user3048027 提问时间:9/2/2022 最后编辑:Daiuser3048027 更新时间:9/2/2022 访问量:197
将 List<dynamic> 强制转换为 IEnumerable<Tuple<string,string 时出错>>
Error in cast List<dynamic> to IEnumerable<Tuple<string,string>>
问:
我在转换 API 响应类型时遇到问题。该 API 以下面给出的特定格式返回代码List<object>
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
dynamic tupleStringList;
tupleStringList = new List<dynamic>{Tuple.Create("a","b"),Tuple.Create("c","d")}; // this data will come API which I have no control
IEnumerable<Tuple<string,string>> test = (IEnumerable<Tuple<string,string>>) tupleStringList;// here we need to cast as another internal function which use it as IEnumerable<Tuple<string,string>>
}
}
我得到的错误如下
运行时异常(第 9 行):无法将类型的对象转换为类型。
'System.Collections.Generic.List`1[System.Object]'
'System.Collections.Generic.IEnumerable`1[System.Tuple`2[System.String,System.String]]'
堆栈跟踪:
[System.InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[System.Object]'`` to type 'System.Collections.Generic.IEnumerable`1[System.Tuple`2[System.String,System.String]]'.] at CallSite.Target(Closure,CallSite,Object ) at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0) at Program.Main() :line 9
答:
1赞
Jeppe Stig Nielsen
9/2/2022
#1
我建议,也许像:tupleStringList.Cast<Tuple<string, string>>()
(IEnumerable<Tuple<string, string>>)(tupleStringList.Cast<Tuple<string, string>>())
(这需要一个指令。using System.Linq;
Ralf 在注释中有一个观点(请参阅扩展方法和动态对象):如果表达式的绑定不考虑扩展方法,则首先转换为非泛型。例如:dynamic
IEnumerable
var tupleStringListCast = (IEnumerable)tupleStringList;
var test = tupleStringListCast.Cast<Tuple<string, string>>();
或者使用通常的静态调用语法进行调用:Cast<TResult>()
var test = (IEnumerable<Tuple<string, string>>)(Enumerable.Cast<Tuple<string, string>>(tupleStringList));
但是,它假设这些对确实是 的类型。Tuple<,>
评论
0赞
Ralf
9/2/2022
...和 tupleStringList 不是动态的,也是;)
0赞
Jeppe Stig Nielsen
9/2/2022
@Ralf被宣布?你是什么意思?tupleStringList
dynamic
0赞
Ralf
9/2/2022
在作者示例中,tupleStringList 被定义为动态的。您将很难在动态上调用 Cast。因此,在需要强制转换疯狂的情况下,您还需要将 tupleStringList 强制转换为 IEnumerable<>以便能够调用 Cast。
1赞
Jeppe Stig Nielsen
9/2/2022
@Ralf 您可以在编译时调用任何内容。一切都编译。因为绑定被推迟到程序运行(运行时)。届时,如果只有实际的运行时类型是实现非泛型的,则扩展方法将适用。情况很可能是这样。另一个问题是生成的实例是否完全属于 类型。这就是为什么我在回答中说“假设”。询问者没有提供任何细节。dynamic
.Cast<TResult>()
tupleStringList
IEnumerable
Tuple<string, string>
0赞
Ralf
9/2/2022
有趣的是,Net 5 在查找 Cast 方法 (RuntimeBinderException) 时遇到了问题,而 Net 6 则没有我想象的那样。但是你说得对,我们缺少一个“完美”合适的答案的背景。
评论
dynamic
Tuple
ValueTuple
List<object>
” - 为什么它不返回强类型的东西,而不是诉诸于装箱所有内容?Object