2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            List<object> list = new List<object>();
            List<Dictionary<string, object>> dict = new List<Dictionary<string, object>>();

            Dictionary<string, object> master = new Dictionary<string, object>();
            master.Add("list", list);
            master.Add("dict", dict);

            List<object> mydict = (List<object>)master["dict"]; // this is where i get exception
            Console.Write("Count: ", mydict.Count);
        }
    }
}

它在粗体线上抛出异常。为什么会出现这种行为,我该如何访问这个元素?谢谢苏曼思

4

4 回答 4

5

因为没有List<object>下dict键

var mydict = (List<Dictionary<string, object>>)master["dict"];
于 2013-08-13T09:14:57.310 回答
3

该值为master["dict"]a List<Dictionary<string, object>>,而代码将其强制转换为 a List<object>。这不起作用,因为在 type 上List<T> 是不变T的。举一个更简单的例子,这是无效的:

var list = new List<string>();
var listOfObjects = (List<object>)list;

如果您以某种方式知道要取出的项目类型,master则可以将其转换回正确的类型:

var masterDict = (List<Dictionary<string, object>>)master["dict"];

或者,您可以将值转换为,IEnumerable<object>因为该接口在其类型参数上是协变的:

// This is not really meaningful because you can cast to non-generic IEnumerable
// just as well, but it works as a demonstration of what is possible.
var mycollection = (IEnumerable<object>)master["dict"];
于 2013-08-13T09:16:59.027 回答
0

您正试图获得一个List<Dictionary<string, object>>作为,List<object>并且可能认为Dictionary<string, object>object正确的?

是的,没错, List<Dictionary<string, object>>不继承,因此您使用的转换无效List<object>

正如我之前的人所说:做

(List<Dictionary<string, object>>)master["dict"];
于 2013-08-13T09:21:23.683 回答
0

如果您需要IEnumerableICollection方法可以转换为非通用接口,例如:

        ICollection mydict = (ICollection)master["dict"];
        Console.Write("Count: ", mydict.Count);
于 2013-08-13T09:23:43.083 回答