我有一个字符串(键)和对象(值)。如何在字典中获取每个值的类型?
示例代码:
Dictionary<string, object> jsonData;
ArrayList arr = new ArrayList();
arr.Add("1");
arr.Add("2");
arr.Add("3");
jsonData["status"] = "200";
jsonData["data"] = arr;
foreach(KeyValuePair<string, object> item in jsonData)
{
item.Value
// type string vs ArrayList ??
}
答案 0 :(得分:0)
您可以尝试使用as
-operator:
foreach(KeyValuePair<string, object> item in jsonData)
{
ArrayList list;
string str;
if ((list = item.Value as ArrayList) != null)
{
}
else if ((str = item.Value as string) != null)
{
}
}
另一种方法是使用is
-operator:
foreach(KeyValuePair<string, object> item in jsonData)
{
if (item.Value is ArrayList)
{
ArrayList list = (ArrayList) item.Value;
}
else if (item.Value is string)
{
string str = (string) item.Value;
}
}