[英]C# dictionary<> missing key
當我做val = dict [“不存在的密鑰”]時,我得到System.Collections.Generic.KeyNotFoundException有沒有辦法讓我的字典調用成員函數,並將密鑰作為生成值的參數?
-edit-也許我應該更具體。 我想AUTOMATICALLY調用一個成員函數來做它需要的東西,為那個鍵創建正確的值。 在這種情況下,它在我的數據庫中創建一個條目然后給我回到它的獨特句柄。 我將在下面發布我的解決方案。
使用擴展方法:
static class DictionaryExtensions {
public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey,TValue> dic, TKey key, Func<TKey, TValue> valueGenerator) {
TValue val;
if (dic.TryGetValue(key, out val))
return val;
return valueGenerator(key);
}
}
你可以用以下方式調用它:
dic.GetValueOrDefault("nonexistent key", key => "null");
或傳遞成員函數:
dic.GetValueOrDefault("nonexistent key", MyMemberFunction);
Object value;
if(dict.TryGetValue("nonexistent key", out value))
{
// this only works when key is found..
}
// no exception is thrown here..
順便說一句 ,你所談論的技術叫做Memoization
TryGetValue()很好。 如果您沒有性能限制或不需要該值,也可以使用ContainsKey()。
if(myDictionary.ContainsKey("TestKey")
{
System.Print(myDictionary["TestKey"]);
}
string Q = "nonexistent key";
string A = "";
if(dict.containskey(Q))
{
A= dict[Q];
}
else
{
//handler code here
}
public class MyDictionary<K, V>
{
Dictionary<K, V> o = new Dictionary<K, V>();
public delegate V NonExistentKey(K k);
NonExistentKey nonExistentKey;
public MyDictionary(NonExistentKey nonExistentKey_)
{ o = new Dictionary<K, V>();
nonExistentKey = nonExistentKey_;
}
public V this[K k]
{
get {
V v;
if (!o.TryGetValue(k, out v))
{
v = nonExistentKey(k);
o[k] = v;
}
return v;
}
set {o[k] = value;}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.