C#三元运算符中的调用函数 [英] Calling functions in C# ternary operator

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

问题描述

为什么此代码无效?相当确定它在C / C ++中是合法的

Why is this code not valid? Pretty sure it's legit in C /C++

伪代码:

String s = Console.ReadLine();
int x = 0;
Int32.TryParse(s, out x) ? Console.WriteLine("Foo") :  Console.WriteLine("bar");


推荐答案

三元运算符用于返回值和那些值

The ternary operator is used to return values and those values must be assigned.

如果要在三元运算符中调用void方法,则可以使用如下委托:

If you want to invoke void methods in a ternary operator, you can use delegates like this:

String s = Console.ReadLine();
int x = 0;
(Int32.TryParse(s, out x) ? new Action(() => Console.WriteLine("Foo")) : () => Console.WriteLine("bar"))();

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

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