【问题标题】:Can't convert List<KeyValuePair<...,...>> to IEnumerable<object>?无法将 List<KeyValuePair<...,...>> 转换为 IEnumerable<object>?
【发布时间】:2011-12-20 13:49:20
【问题描述】:

尝试这样的事情时得到一个 InvalidCastException :

IEnumerable<object> test = (IEnumerable<object>)new List<KeyValuePair<string, int>>();

但是,这确实有效:

IEnumerable<object> test = (IEnumerable<object>)new List<Dictionary<string, int>>();

那么最大的不同是什么?为什么 KeyValuePair 不能转化为对象?

更新:我应该指出这确实有效:

object test = (object)KeyValuePair<string,string>;

【问题讨论】:

    标签: c#


    【解决方案1】:

    那是因为KeyValuePair&lt;K,V&gt; 不是一个类,是一个结构。要将列表转换为 IEnumerable&lt;object&gt; 意味着您必须获取每个键值对并将其装箱:

    IEnumerable<object> test = new List<KeyValuePair<string, int>>().Select(k => (object)k).ToList();
    

    由于您必须转换列表中的每个项目,因此您不能通过简单地转换列表本身来做到这一点。

    【讨论】:

      【解决方案2】:

      因为它是一个结构,而不是一个类:http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx

      【讨论】:

        【解决方案3】:

        KeyValuePair 是一个结构体,不继承自类对象。

        【讨论】:

          【解决方案4】:

          首先 Dictionary 已经是 KeyValuePairs 的集合,因此第二个示例是将整个 Dictionary 转换为一个对象,而不是 KeyValuePairs。

          无论如何,如果要使用List,则需要使用Cast方法将KeyValuePair结构转换为对象:

          IEnumerable<object> test = (IEnumerable<object>)new List<KeyValuePair<string, int>>().Cast<object>();
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2019-09-17
            • 1970-01-01
            • 1970-01-01
            • 2013-06-12
            • 1970-01-01
            • 2012-02-24
            • 1970-01-01
            相关资源
            最近更新 更多