在If条件中进行内联TryGetValue并评估其值 [英] In-line TryGetValue in If conditon and evaluate it's Value

查看:102
本文介绍了在If条件中进行内联TryGetValue并评估其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以在If条件中的一行上编写TryGetValue.调用TryGetValue的正常方法是:

Is there any way how to write TryGetValue on one line in If condition. Normal way of calling TryGetValue would be:

string value;
Dictionary.TryGetValue("Key", out value);
If(value == "condition") { ... }

我想要的就是这样.

If(Dictionary.TryGetValue("Key", out string) == "Condition") { ... }

我知道该行不起作用,但是它显示了所需的结果.

I know that line wouldn't work, however it shows what is desired result.

有什么方法可以实现这一目标吗?

Is there any way how to achieve this?

推荐答案

您需要先使用返回的bool,但是随后您可以使用out参数(带有> = C#7):

You need to use the returned bool first but then you can use the out parameter(with >= C# 7):

if (Dictionary.TryGetValue("Key", out string value) && value == "Condition")
{
    //...
}

MSDN :

从C#7.0开始,您可以在参数中声明out变量 方法调用列表,而不是单独的变量 声明.

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,或者希望它更短一些,则可以使用此扩展名:

If you're not using C#7 or you want it even shorter you could use this extension:

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"))
{
    //...
}

这篇关于在If条件中进行内联TryGetValue并评估其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆