c#

c#中trygetvalue的作用是什么

小亿
240
2024-04-18 10:28:08
栏目: 编程语言

TryGetValue 是用于在 C# 中检索 DictionaryHashtable 中的元素的方法。它将尝试获取与指定键关联的值,并返回一个布尔值,指示是否成功找到该键。如果成功找到,则该方法将返回与键关联的值,并将其存储在一个输出参数中,否则返回默认值。

示例代码如下:

Dictionary<string, int> dict = new Dictionary<string, int>();
dict["key1"] = 1;
dict["key2"] = 2;

int value;
if (dict.TryGetValue("key1", out value))
{
    Console.WriteLine("The value associated with key1 is: " + value);
}
else
{
    Console.WriteLine("Key1 not found in the dictionary");
}

if (dict.TryGetValue("key3", out value))
{
    Console.WriteLine("The value associated with key3 is: " + value);
}
else
{
    Console.WriteLine("Key3 not found in the dictionary");
}

在上面的示例中,TryGetValue 方法用于检索字典中两个键的值,并根据结果输出相应的消息。

0
看了该问题的人还看了