阅读量:3
在C#中,TryGetValue是一个字典(Dictionary)类的方法,用于尝试获取指定键的值。如果键存在,则返回该值;否则返回默认值。以下是如何使用TryGetValue的示例:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个字典
Dictionary<string, int> myDictionary = new Dictionary<string, int>
{
{"apple", 1},
{"banana", 2},
{"orange", 3}
};
// 尝试获取键为 "apple" 的值
int value;
if (myDictionary.TryGetValue("apple", out value))
{
Console.WriteLine($"The value of 'apple' is: {value}");
}
else
{
Console.WriteLine("The key 'apple' does not exist in the dictionary.");
}
// 尝试获取不存在的键 "grape" 的值
if (myDictionary.TryGetValue("grape", out value))
{
Console.WriteLine($"The value of 'grape' is: {value}");
}
else
{
Console.WriteLine("The key 'grape' does not exist in the dictionary.");
}
}
}
在这个示例中,我们首先创建了一个包含三个键值对的字典。然后,我们使用TryGetValue方法尝试获取键为 “apple” 的值。如果键存在,我们将输出该值;否则,我们将输出一个消息表示键不存在。接下来,我们尝试获取不存在的键 “grape” 的值,并输出相应的消息。
以上就是关于“c# trygetvalue 如何用”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm