我有一个简单的字典调用结果:
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() )谢谢!