三元运营商在C# [英] Ternary operators in C#

查看:170
本文介绍了三元运营商在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用三元运算符,就可以像做以下(假设FUNC1()和FUNC2()返回一个int:

With the ternary operator, it is possible to do something like the following (assuming Func1() and Func2() return an int:

int x = (x == y) ? Func1() : Func2();

不过,有没有什么办法可以做同样的事情,不返回值?例如,像(假设FUNC1()和FUNC2()返回void):

However, is there any way to do the same thing, without returning a value? For example, something like (assuming Func1() and Func2() return void):

(x == y) ? Func1() : Func2();

我意识到这可以用一个if语句来完成,我只是想知道是否有办法做到这一点是这样的。

I realise this could be accomplished using an if statement, I just wondered if there was a way to do it like this.

推荐答案

奇怪,但你可以做

class Program
{
    private delegate void F();

    static void Main(string[] args)
    {
        ((1 == 1) ? new F(f1) : new F(f2))();
    }

    static void f1()
    {
        Console.WriteLine("1");
    }

    static void f2()
    { 
        Console.WriteLine("2");
    }
}

这篇关于三元运营商在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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