铸造匿名类型的列表,以动态对象的名单 [英] Cast List of Anonymous type to List of Dynamic Objects

查看:198
本文介绍了铸造匿名类型的列表,以动态对象的名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能投了列表< AnonymousObject> 列表<动态> ?我有这样的下面的代码:

Why can't I cast a List<AnonymousObject> to a List<dynamic>? I have this following code:

var datasource = someList.Select(o => new { x = o.A, y = o.B });
dgvSomeGridView.DataSource = datasource.ToList();
dgvSomeGridView.DataBind();



然后我访问 GridView.DataSource 与下面的代码:

var ds = ((List<dynamic>)dgvSomeGridView.DataSource);
....



但它在那里我将它转换为行抛出一个错误列表<动态> ,它说:

无法投类型的对象 System.Collections.Generic.List'1 [<> f__AnonymousType0'8 [System.Int32,System.String] 键入 System.Collections中.Generic.List'1 [System.Object的]

Unable to cast object of type System.Collections.Generic.List'1[<>f__AnonymousType0'8[System.Int32,System.String]] to type System.Collections.Generic.List'1[System.Object].

为什么我不能投了名单匿名类型到动态,或错误到对象说键入?我怎样才能解决这个问题?

Why can't I cast a list of anonymous type to a dynamic, or as the error says to an object type? How can I resolve this?

我的代码是在C#中,框架4.0,打造VS2010临,平台是ASP.NET。

My Code is in C#, framework 4.0, build in VS2010 Pro, platform is ASP.NET.

请帮忙,谢谢提前

推荐答案

由于列表< T> 在变,没有共同的变体,所以你必须的的成的IEnumerable<动态> 支持合作变种:

Since List<T> is in-variant, not co-variant, so you have to cast into IEnumerable<dynamic> which supports co-variant:

var ds = ((IEnumerable<dynamic>)dgvSomeGridView.DataSource).ToList();

有关更多的有关协变

这篇关于铸造匿名类型的列表,以动态对象的名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆