【发布时间】:2013-03-21 13:11:05
【问题描述】:
我想使用 TryGetValue 方法访问字典保险箱上的某个属性。
例如,我会像这样直接访问的条目:
jsonObject[prop1][prop2][0][prop3]
有什么方便的方法吗?
【问题讨论】:
-
如果值不存在,你期望它做什么?
jsonObject是什么类型的?
标签: c# json dictionary json.net trygetvalue
我想使用 TryGetValue 方法访问字典保险箱上的某个属性。
例如,我会像这样直接访问的条目:
jsonObject[prop1][prop2][0][prop3]
有什么方便的方法吗?
【问题讨论】:
jsonObject是什么类型的?
标签: c# json dictionary json.net trygetvalue
这是一个想法(未经测试)。它确实假定嵌套的 IDictionary 至少与指定的键数一样深,并且在 object 中工作(您当然可以做一些事情使其成为通用的):
bool TryGetNestedValue (this IDictionary dict, out object value,
params object[] keys)
{
for(int i = 0; i < keys.Length; i++)
{
var key = keys[i];
if (!dict.Contains(key))
{
value = null;
return false;
}
if (i == keys.Length - 1)
{
value = dict[key];
return true;
}
dict = dict[key];
}
throw new ArgumentException("keys");
}
【讨论】: