有什么方法可以在 If 条件下将 TryGetValue 写在一行上。调用 TryGetValue 的正常方式是:
string value;
Dictionary.TryGetValue("Key", out value);
If(value == "condition") { ... }
我正在寻找的是这样的东西。
If(Dictionary.TryGetValue("Key", out string) == "Condition") { ... }
我知道该行行不通,但它显示了所需的结果。
有什么办法可以实现吗?
最佳答案
您需要先使用返回的 bool
,然后您可以使用 out
参数(使用 >= C# 7):
if (Dictionary.TryGetValue("Key", out string value) && value == "Condition")
{
//...
}
MSDN :
Starting with C# 7.0, you can declare the out variable in the argument list of the method call, rather than in a separate variable declaration.
如果您不使用 C#7 或者您希望它更短,您可以使用这个扩展:
public static bool TryEvaluateValue<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, Func<TValue, bool> evalValue)
{
TValue val;
if(!dict.TryGetValue(key, out val))
return false;
return evalValue(val);
}
然后你的if
条件变成:
if (Dictionary.TryEvaluateValue("Key", value => value == "Condition"))
{
//...
}
关于c# - 在 If 条件中内联 TryGetValue 并评估其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52362941/