- .NET Framework : 4.7.2
- IDE : Visual Studio Community 2022
- OS : Windows 10 x64
- typesetting : Markdown
- blog : niaoge.blog.csdn.net
ContainsKey的定义
命名空间:
System.Collections.Generic
程序集:
System.Collections.dll
原型
public bool ContainsKey (TKey key);
确定是否 Dictionary<TKey,TValue> 包含指定键。
参数
key TKey
要在 Dictionary<TKey,TValue> 中定位的键。
返回
Boolean
如果 true 包含具有指定键的元素,则为 Dictionary<TKey,TValue>;否则为 false。
示例代码
代码
csharp
using System;
using System.Collections.Generic;
namespace Niaoge
{
class Program
{
static void Main(string[] args)
{
// 新建字典
var d = new Dictionary<string, string>();
// 向字典中添加内容
d.Add("key1", "value1");
d.Add("key2", "value2");
d.Add("key3", "value3");
if (d.ContainsKey("key1"))
{
Console.WriteLine("key1已经存在");
}
else
{
Console.WriteLine("key1不存在");
}
if (d.ContainsKey("haha"))
{
Console.WriteLine("haha已经存在");
}
else
{
Console.WriteLine("haha不存在");
}
Console.ReadKey();
}
}
}
运行结果
key1已经存在
haha不存在
参考
文档\]