我有一個簡單的字典呼叫結果:
Dictionary<String,String> results=new();
results["a"]="a";
results["b"]="b";
results["c"]="c";
為了簡化示例,我的字典僅包含 3 個字母鍵 a、b、c。但有時它不會包含這些值之一,甚至不包含,(它總是會被初始化)。假設這種情況:
Dictionary<String,String> results=new();
if(anyconditionA) results["a"]="a";
if(anyconditionB)results["b"]="b";
if(anyconditionC)results["c"]="c";
所以每次我想用這本字典操作時,我都必須檢查鍵值: var test= results["a"]; -> 如果 anycontitionA 不為真,則拋出 System.Collections.Generic.KeyNotFoundException。所以為了解決這個問題,我這樣做:
if(results.ContainsKey("a"){
someOperation(results["a"]);
}
所以如果我有很多值代碼看起來像:
if(results.ContainsKey("a"){someOperation(results["a"]);}
if(results.ContainsKey("b"){... stuff}
if(results.ContainsKey("c"){... stuff}
if(results.ContainsKey("..."){... stuff}
if(results.ContainsKey("d"){someOperation(results["d"]);}
?是否有一種正確的方法可以在一個陳述句中執行此操作,我的意思是檢查并執行操作是否存在,或者我必須在每次該值存在時進行測驗?(就像在串列中使用 null 運算子類似 results[a]?.someOperation() )謝謝!
uj5u.com熱心網友回復:
如果您發現自己經常這樣做并且想要簡化呼叫代碼,則可以撰寫一個擴展方法:
public static class DictionaryExt
{
public static bool DoIfExists<TKey, TValue>(this Dictionary<TKey, TValue> self, TKey key, Action<TValue> action)
{
if (!self.TryGetValue(key, out var value))
return false;
action(value);
return true;
}
}
然后你可以寫這樣的代碼:
results.DoIfExists("a", someOperation);
results.DoIfExists("b", value => Console.WriteLine("Doing stuff with " value));
results.DoIfExists("c", value =>
{
Console.WriteLine("Doing stuff with " value);
Console.WriteLine("This uses multiple lines.");
});
我真的不確定這是否值得(我不喜歡過度使用擴展方法),但這是一個見仁見智的問題!
在我看來,上面的第三個例子混淆了代碼,最好寫成:
if (results.TryGetValue("c", out var value))
{
Console.WriteLine("Doing stuff with " value);
Console.WriteLine("This uses multiple lines.");
}
但第一個例子results.DoIfExists("a", someOperation);可以說比以下更簡單:
if (results.TryGetValue("a", out var value))
someOperation(value);
這是一個微小的改進,我個人不會打擾。由你決定!
uj5u.com熱心網友回復:
您從 Matthew Watson 那里得到了“如果鍵不在字典中,則可能不要呼叫取值的操作”,但是在您的問題結束時,您問了一個稍微不同的問題
?是否有一種正確的方法可以在一個陳述句中執行此操作,我的意思是檢查并執行操作是否存在,或者我必須在每次該值存在時進行測驗?(就像在串列中使用 null 運算子類似 results[a]?.someOperation() )謝謝!
如果操作是對字典中的值的方法,那么可以肯定,您可以使用?.來防止對不存在的值的空參考:
var dictionary = new Dictionary<int, StringBuilder>();
dictionary.GetValueOrDefault(1)?.AppendLine("hello");
GetValueOrDefault作為擴展方法實作,是 .net 核心 2.2 的東西。有一些 nuget 包使其可用于舊版本,或者您可以自己撰寫它作為擴展,可能會從netcore 源中改編它并將其放入您的應用程式中:
public static TValue? GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key)
{
return dictionary.GetValueOrDefault(key, default!);
}
public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
{
if (dictionary == null)
{
throw new ArgumentNullException(nameof(dictionary));
}
TValue? value;
return dictionary.TryGetValue(key, out value) ? value : defaultValue;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/342487.html
標籤:C# 。网 林克 字典 keynotfound异常
下一篇:Linq按相關物體分組
