C# TryGetValue(TKey,TValue):获取具有指定键的值

  • Post category:C#

C#中的TryGetValue方法是Dictionary类提供的一种方式,用于获取指定键的值,并检查是否存在该键。如果存在该键,则TryGetValue方法返回true并将相应的值存储在参数out TValue value中;否则,返回false并将value参数设置为值类型或null。

下面是一个示例,演示如何使用TryGetValue来获取Dictionary对象中的键值:

Dictionary<string, int> myDictionary = new Dictionary<string, int>();
myDictionary.Add("one", 1);
myDictionary.Add("two", 2);
myDictionary.Add("three", 3);

int value;
if (myDictionary.TryGetValue("two", out value)){
    Console.WriteLine(value);   // output: 2
} else {
    Console.WriteLine("Key not found");
}

该示例创建了一个Dictionary对象,并向其添加三个键值对。然后,它使用TryGetValue方法来尝试获取myDictionary中的“two”键的值。在此情况下,TryGetValue方法返回true,并将键“two”对应的值2存储在value变量中。

下面是另一个示例,演示如何使用TryGetValue来避免在尝试获取不存在的键值对时报错:

Dictionary<string, int> myDictionary = new Dictionary<string, int>();
myDictionary.Add("one", 1);
myDictionary.Add("two", 2);

int value;
if (myDictionary.TryGetValue("three", out value)){
    Console.WriteLine(value);
} else {
    Console.WriteLine("Key not found");  // output: Key not found
}

该示例创建了一个包含两个键值对的Dictionary对象,并尝试使用TryGetValue方法获取一个不存在的键“three”的值。由于键“three”不存在,TryGetValue方法返回false,并将value参数设置为其值类型的默认值0。在此情况下,输出为“Key not found”。

总之,TryGetValue方法是Dictionary类的一种有用工具,它允许开发人员在获取Dictionary对象中不存在的键的值时,避免出现异常。