C# 在 运行 时间将 Enumerable.Iterator 转换为已知列表 <Object>

C# Cast Enumerable.Iterator to known List<Object> at run time

我有一个只能在运行时检索对象类型的方法。我试图将其转换为已知对象列表,但我失败了。

  private string outputParamForListOrDict(IMethodReturn returnValue)
    {
        StringBuilder sb = new StringBuilder();
        String outputString = string.Empty;

        switch (returnValue.ReturnValue.GetType().GetGenericArguments()[0].Name)
        {       

            case nameof(ViewDocumentReport):

                List<ViewDocumentReport> _viewDocumentParam = (List<ViewDocumentReport>)returnValue.ReturnValue;

                //process the data here........

                return sb.ToString();

            //Other object cases

         }
    }

我遇到了以下异常:

"Unable to cast object of type >'<TakeIterator>d__25`1[ezAcquire.RMS.Model.ViewModels.ViewDocumentReport]' to type 'System.Collections.Generic.List`1[ezAcquire.RMS.Model.ViewModels.ViewDocumentReport]'."}

我在调试模式下放置了一个断点。 我的 returnValue.ReturnValue 属于

如果展开,我可以看到列表列表。

有人可以向我解释一下 d_25 是什么意思,并建议我如何在运行时正确地转换它吗?

谢谢

如果您非常确定您的对象是您知道的类型的 IEnumerable,您可以在执行 ToList.

之前将该对象转换为 IEnumerable<T>
public class Test {

}

void Main()
{
    object x = Enumerable.Range(0,100).Select(_ => new Test()).Take(15);
    List<Test> fail = (List<Test>)x; // InvalidCastException: Unable to cast object of type '<TakeIterator>d__25`1[UserQuery+Test]' to type 'System.Collections.Generic.List`1[UserQuery+Test]'.
    List<Test> pass = ((IEnumerable<Test>)x).ToList(); // No problem
}

直接从 IEnumerable<T> 转换为 List<T> 是无效的转换,正如您遇到的那样。在将其输入 List<T> 构造函数或使用 Linq 的 ToList 方法之前,您需要将 object 转换为 IEnumerable