可以通过以下步骤实现:
public static TValue GetValue<TKey, TValue>(Dictionary<TKey, TValue> dictionary, TKey key)
{
TValue value;
dictionary.TryGetValue(key, out value);
return value;
}
Dictionary<string, int> myDictionary = new Dictionary<string, int>();
myDictionary.Add("key1", 10);
myDictionary.Add("key2", 20);
int value = GetValue(myDictionary, "key1");
Console.WriteLine(value); // 输出:10
这个方法适用于任何类型的字典,可以根据需要进行调整和扩展。它可以帮助我们在C#中方便地从字典中获取值,提高代码的可读性和可维护性。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云