简体   繁体   English

演员表错误<dynamic>到 IEnumerable <tuple<string,string> &gt; </tuple<string,string></dynamic>

[英]Error in cast List<dynamic> to IEnumerable<Tuple<string,string>>

I am facing an issue while casting an API response type.我在投射 API 响应类型时遇到问题。 The API returns List<object> in a particular format code given below 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>>
    }
}

The error I am getting is given below我得到的错误如下

Run-time exception (line 9): 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]]' . Run-time exception (line 9): 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]]'

Stack Trace:堆栈跟踪:

 [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

I suggest tupleStringList.Cast<Tuple<string, string>>() , maybe like:我建议tupleStringList.Cast<Tuple<string, string>>() ,也许像:

(IEnumerable<Tuple<string, string>>)(tupleStringList.Cast<Tuple<string, string>>())

(This needs a using System.Linq; directive.) (这需要using System.Linq;指令。)

Ralf has a point in the comments (see Extension method and dynamic object ): If extensions methods are not considered for the binding of a dynamic expression, cast to nongeneric IEnumerable first. Ralf 在评论中有一点(请参阅扩展方法和动态 object ):如果不考虑扩展方法来绑定dynamic表达式,请先转换为非泛型IEnumerable For example:例如:

var tupleStringListCast = (IEnumerable)tupleStringList;
var test = tupleStringListCast.Cast<Tuple<string, string>>();

Or call Cast<TResult>() with usual static call syntax:或使用通常的 static 调用语法调用Cast<TResult>()

var test = (IEnumerable<Tuple<string, string>>)(Enumerable.Cast<Tuple<string, string>>(tupleStringList));

However, it assumes the pairs are really of type Tuple<,> .但是,它假定这些对实际上是Tuple<,>类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM