/// <summary>
/// 通过键获取值的方法
/// </summary>
public static TValue GetValueByKey<TKey, TValue>(Dictionary<TKey, TValue> dictionary, TKey key)
{
TValue value;
// 使用TryGetValue方法来尝试获取值
if (dictionary.TryGetValue(key, out value))
{
// 如果成功获取到值,则返回对应的值
return value;
}
else
{
value = default(TValue);
// 如果未找到对应的键,则返回一个默认值或者抛出异常
return value;
}
}
使用方法获取值
//int value = GetValueByKey(myDictionary, "banana");
//Debug.Log(value); // 输出
/// <summary>
/// 通过值获取键的方法
/// </summary>
public static TKey GetKeyByValue<TKey, TValue>(Dictionary<TKey, TValue> dictionary, TValue value)
{
foreach (var pair in dictionary)
{
if (EqualityComparer<TValue>.Default.Equals(pair.Value, value))
{
return pair.Key;
}
}
throw null;
//throw new KeyNotFoundException("The value was not found in the dictionary.");
}
08-03
1972

11-16
2551
