阅读量:4
在C#中,要判断KeyValuePair中的键(Key)或值(Value)是否为特定类型,可以使用泛型和is关键字。以下是一个示例:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个KeyValuePair列表
Liststring, object>> keyValuePairs = new Liststring, object>>
{
new KeyValuePair<string, object>("name", "John"),
new KeyValuePair<string, object>("age", 30),
new KeyValuePair<string, object>("city", "New York")
};
// 遍历列表并检查键和值的类型
foreach (KeyValuePair<string, object> kvp in keyValuePairs)
{
// 检查键是否为string类型
if (kvp.Key is string key && key == "name")
{
Console.WriteLine("Found a key of type string with value: " + kvp.Value);
}
// 检查值是否为int类型
if (kvp.Value is int value && value == 30)
{
Console.WriteLine("Found an int value with key: " + kvp.Key);
}
}
}
}
在这个示例中,我们创建了一个包含三个KeyValuePair的列表。然后,我们遍历列表并使用is关键字检查每个键和值的类型。如果找到符合条件的键或值,我们将输出相应的信息。
以上就是关于“c# keyvaluepair怎样判断”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm