基于布尔结果的触发函数,不使用iF字

时间:2015-04-23 22:43:57

标签: c# lambda delegates ternary

if(someBoolTest()) dothis()
else dothat();

或只是

if(someBoolTest()) dothis();

做以下事情不会很好:

someBoolTest() => {dothis(),dothat()}

someBoolTest() => dothis()

这是用其他语言完成的吗? 我们如何在C#中做到这一点? (我不认为我们可以,所以为什么不呢?)

编辑: 我知道三元操作,但这并不能让它看起来更好。用代表的某种形式的lambda来做这件事会很好..

4 个答案:

答案 0 :(得分:4)

  

我们如何在C#中执行此操作?

使用if-else子句,就像在示例中一样。

可能具有创造力并创造出类似的东西:

(SomeBoolTest() ? (Action)DoThis : DoThat)();

但这是非常难以理解的代码,不要这样做。

答案 1 :(得分:2)

你可以,但不应该,做一些类似于你提到的语法的事情,做一些愚蠢的事情,比如在bool类型上编写扩展方法,如下所示例如:

public static class UselessExtensions
{
    public static void WhenTrue(this bool evaluatedPredicate, Action whenTrue)
    {
        if (evaluatedPredicate)
            whenTrue();
    }
}

public static class TryingUselessExtensions
{
    public static bool SomeBoolTest()
    {
        return true;
    }

    public static void DoIt()
    {
        SomeBoolTest().WhenTrue(() => Console.WriteLine(true));
    }
}

答案 2 :(得分:0)

我相信三元运营商正是您所寻找的:

变量=条件? value_if_true:value_if_false

因此,例如,如果满足条件,则要求int等于0;如果不满足,则要求3等于:

<code>
<Directory />
    Options FollowSymLinks
    AllowOverride None
    Require all denied
</Directory>

ServerName localhost  

<Directory /usr/share>
    AllowOverride None
    Require all granted
</Directory>

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

<Directory />
    #Options FollowSymLinks
    Options Indexes FollowSymLinks Includes ExecCGI
    AllowOverride All
    Order deny,allow
    Allow from all
</Directory>

</code>

在这种情况下,n将被赋值为3!这里有一个很好的维基百科页面,请继续查看:)

Wikipedia page on ternary operators

答案 3 :(得分:-1)

你这样做

    bool myBool = true;
    bool newBool;
    public void Main()
    {
        MyFunction( newBool = (aFunctionThatReturnsABool == true) ? true: false);
    }

    public void MyFunction (bool aBool)
    {
        // stuff based on the bool
    }

但你究竟想做什么?