C# 在运行时将 Enumerable.Iterator 转换为已知的 List<Object>

csa*_*ong 1 c# casting list enumerable custom-object

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

  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

         }
    }
Run Code Online (Sandbox Code Playgroud)

我在下面遇到了一个例外:

"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]'."}
Run Code Online (Sandbox Code Playgroud)

我在调试模式下设置了断点。我的 returnValue.ReturnValue 是System.Linq.Enumrable.<TakeIterator>

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

列表<ViewDocumentREport>

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

谢谢

Jon*_*ase 5

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

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
}
Run Code Online (Sandbox Code Playgroud)

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