c#dictionary 的值可以有哪些类型
2个回答
展开全部
增加键值对之前需要判断是否存在该键,如果已经存在该键而且不判断,将抛出异常。所以这样每次都要进行判断,很麻烦,在备注里使用了一个扩展方法
public static void DicSample1()
{
Dictionary<String, String> pList = new Dictionary<String, String>();
try
{
if (pList.ContainsKey("Item1") == false)
{
pList.Add("Item1", "ZheJiang");
}
if (pList.ContainsKey("Item2")== false)
{
pList.Add("Item2", "ShangHai");
}
else
{
pList["Item2"] = "ShangHai";
}
if (pList.ContainsKey("Item3") == false)
{
pList.Add("Item3", "BeiJiang");
}
}
catch (System.Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
}
//判断是否存在相应的key并显示
if (pList.ContainsKey("Item1"))
{
Console.WriteLine("Output: " + pList["Item1"]);
}
//遍历Key
foreach (var key in pList.Keys)
{
Console.WriteLine("Output Key: {0}", key);
}
//遍历Value
foreach (String value in pList.Values)
{
Console.WriteLine("Output Value: {0}", value);
}
//遍历Key和Value
foreach (var dic in pList)
{
Console.WriteLine("Output Key : {0}, Value : {1} ", dic.Key, dic.Value);
}
}
public static void DicSample1()
{
Dictionary<String, String> pList = new Dictionary<String, String>();
try
{
if (pList.ContainsKey("Item1") == false)
{
pList.Add("Item1", "ZheJiang");
}
if (pList.ContainsKey("Item2")== false)
{
pList.Add("Item2", "ShangHai");
}
else
{
pList["Item2"] = "ShangHai";
}
if (pList.ContainsKey("Item3") == false)
{
pList.Add("Item3", "BeiJiang");
}
}
catch (System.Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
}
//判断是否存在相应的key并显示
if (pList.ContainsKey("Item1"))
{
Console.WriteLine("Output: " + pList["Item1"]);
}
//遍历Key
foreach (var key in pList.Keys)
{
Console.WriteLine("Output Key: {0}", key);
}
//遍历Value
foreach (String value in pList.Values)
{
Console.WriteLine("Output Value: {0}", value);
}
//遍历Key和Value
foreach (var dic in pList)
{
Console.WriteLine("Output Key : {0}, Value : {1} ", dic.Key, dic.Value);
}
}
2016-04-01
展开全部
请看Dictionary的使用介绍:
Dictionary<String, object>
也就是说 只要基类是obejct类型的,都可以作为dictionary的值!
Dictionary<String, object>
也就是说 只要基类是obejct类型的,都可以作为dictionary的值!
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询