您的位置:首页 > 编程语言 > C#

C#控制台基础 往hashtable中再次添加已存在的键值对,会出现异常,应用containskeys解决

2016-09-06 18:04 429 查看
慈心积善融学习,技术愿为有情学。善心速造多好事,前人栽树后乘凉。我今于此写经验,愿见文者得启发。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add(1, "hello");
ht.Add(2,"world");
ht.Add(1, 1);
foreach (var item in ht.Keys)//由键找值
{
Console.WriteLine("键是{0},对应的值是{1}",item,ht[item]);
}

Console.ReadKey();
}
}
}




那么该如何解决呢?

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add(1, "hello");
ht.Add(2,"world");
if (!ht.ContainsKey(1))
{
ht.Add(1, 1);
}
else
{
Console.WriteLine("不可以添加");
}
foreach (var item in ht.Keys)//由键找值
{
Console.WriteLine("键是{0},对应的值是{1}",item,ht[item]);
}

Console.ReadKey();
}
}
}




感恩曾经帮助过 心少朴 的人。

C#优秀,值得学习。Console,ASP.NET,Winform,WPF,设计模式等都可以关注一下,眼界要开阔。

Visual Studio IDE很好用,推荐!

注:此文是自学笔记所生,质量中等,故要三思而后行。新手到此,不可照搬,应先研究其理象数,待能变通之时,自然跳出深坑。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: