[英]Convert object of type List<object> to List<string>
I'm parsing a JSON string using MiniJson in Unity. 我在Unity中使用MiniJson解析JSON字符串。 Now I have a value that's a list of strings. 现在,我有一个字符串列表的值。 Though I get this an object. 虽然我得到这个对象。 The underlying type of the object is a List<object>
, but actually it should be a List<string>
. 对象的基础类型是List<object>
,但实际上它应该是List<string>
。 So currently I do this: 所以目前我这样做:
void SetInfo(Dictionary<string,object> info) {
Colors = (info["colors"] as List<object>).OfType<string>().ToList();
}
The dictionary is what I get from the MiniJson library. 字典是我从MiniJson库中获得的。 This works perfectly. 这很完美。 Though seems a bit ugly, a lot of unnecessary casting, and I was wondering if there's a better way of doing this. 尽管看起来有些丑陋,但有很多不必要的转换,我想知道是否有更好的方法可以做到这一点。 Mostly I'm looking for cleaner code, and faster execution, since there are a lot of these entries. 通常,我正在寻找更干净的代码,以及更快的执行速度,因为这些条目很多。
Edit: I wasn't very clear about this. 编辑:我对此不太清楚。 In the info dictionary there are a bunch of key/value pairs, the type of the values vary. 在信息字典中,有一堆键/值对,值的类型各不相同。 I can cast most very easily, but the info["colors"] object is the one I'm having problems with. 我可以非常轻松地进行转换,但是info [“ colors”]对象是我遇到问题的对象。
So when I do info["colors"]
I get an object
, with an underlying type List<object>
. 所以,当我做info["colors"]
我得到一个object
,具有基础类型List<object>
The objects
in this list are actually strings
. 此列表中的objects
实际上是strings
。
Also, there's not really a performance problem here, since it's only called once at the start of the program, though there is a noticeable lag currently, I'm going to put it on it's own thread anyway so no problem there. 另外,这里并没有真正的性能问题,因为它在程序开始时仅被调用一次,尽管当前存在明显的滞后,但无论如何我还是要把它放在它自己的线程上,所以那里没有问题。 The faster execution is just out of curiosity. 更快的执行速度只是出于好奇。
Try this one. 试试这个。
(info["colors"] as List<object>).ConvertAll(input => input.ToString());
you can also use direct cast (string)input
or input as string
which is even faster(there were debates on casting here at stackoverflow). 您还可以使用直接转换(string)input
或将input as string
,这甚至更快(在stackoverflow上有关于转换的争论)。
info["colors"] as List<object>
can result in null, so I'd rather be more safe and wrap your code like this: info["colors"] as List<object>
可能导致null,所以我宁愿更安全地包装您的代码,如下所示:
List<object> colors = info["colors"] as List<object>;
List<string> typedColors = null;
if (colors!=null)
{
typedColors = colors.ConvertAll(input => input as string);
}
I know this code is a bit old school, but we all know what it means: 我知道这段代码有点老套了,但是我们都知道这意味着什么:
List<object> l = new List<object>();
List<string> s = new List<string>();
foreach( var i in l )
s.Add((string)i);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.