如何从对象中的词典访问值? [英] How do I access values from a Dictionary in an object?

查看:52
本文介绍了如何从对象中的词典访问值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我不确定是否要问正确的问题,但是可以了.我正在使用 Javascript .NET 来解析Javascript对象数组.我的代码如下所示:

Alright, I'm not sure if I'm asking the right question, but here goes. I'm using Javascript .NET to parse a Javascript object array. My code looks something like this:

object packlist;
using (var context = new JavascriptContext())
{
    context.Run(@"function packlist() { this.packs = new Array(); }
                var packlist = new packlist();
                packlist.packs[0] = { item1:""something"", item2:""something2"", item3:""something3"" };
                packlist.packs[1] = { item1:""something"", item2:""something2"", item3:""something3"" };
                packlist.packs[2] = { item1:""something"", item2:""something2"", item3:""something3"" };");
    packlist = context.GetParameter("packlist");
}

在调试时,本地"窗口显示该对象看起来像> 我的问题是如何从packlist.packs[0]访问item1?

While debugging, the Locals window says the object looks like this My question would be how would I go about accessing item1 from packlist.packs[0]?

推荐答案

一般结构如下:

PackList => Dictionary of <string, Dictionary<string,object>[]>

这意味着它是一本字典,其中每个值都是字典中的一类.

Meaning it is a dictionary where each value is an arry of dictionaries.

应该是

object[] arr = packlist["packs"] as object[]; 
Dictionary<string, object> dictPack = arr[0] as Dictionary<string, object>;
object item1 = dictPack["item1"];

object packs;
if (packlist.TryGetValue("packs",out packs)) { 
     object[] arr = packs as object[]; 
     Dictionary<string, object> dictPack = arr[0] as Dictionary<string, object>;
     object item1 = dictPack["item1"];
}

它们之间的区别是,在第一个中,假定键存在于字典中,否则会引发异常.在第二步中,它将尝试获取值并告诉您密钥是否有效.

The difference between them is that in the first, it is assumed that the key exists in the dictionary otherwise it throws an exception. In the second, it will try to get the value and tell you if the key is valid.

要检查关键字是否在字典中,可以使用以下方法:

To check if a key is in the dictionary you can use this:

bool exists = packlist.ContainsKey("item1");

遍历字典中的所有项目

foreach KeyPairValue<string,object> kp in packlist
{
    string key =  kp.Key;
    object value = kp.Value;
}

这是字典类的MSDN链接

Here's the MSDN link for the dictionary class

http://msdn.microsoft.com/fr-fr/library/bb347013.aspx

这篇关于如何从对象中的词典访问值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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