有人可以用简单的英语或伪代码解释三元运算符吗? [英] Could someone explain ternary operators in plain English or pseudocode?

查看:232
本文介绍了有人可以用简单的英语或伪代码解释三元运算符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不理解下面几行中使用的语法,除了它遵循似乎被称为三元运算符的基本结构。

I don't understand the syntax used in the following lines, except that it follows a basic structure of what seems to be called a ternary operator.

string path = args == null || args.Length == 0 ?
    @"C:\GENERIC\SYSTEM\PATH" :
    args[1];

我是这种语法的新手。有人会帮助我将它翻译成真实的英语(或伪代码)吗,就像if语句可以变成 if this then that吗?

I'm new to this syntax. Would someone help me translate it into real English (or pseudocode), much in the way an if statement can be turned into "if this then that"?

编辑:谢谢大家,为您提供答案,都对您有所帮助。不幸的是,我只能投票给你们中的一个,但我会投票支持你们!

Thank you everyone for your answers, you've all been extremely helpful. Unfortunately I can only vote one of you, but I'll upvote a bunch of you!

推荐答案

您所看到的是特殊条件运算符三元运算符。 (而且这里是一个不错的教程)

What you are seeing is a special conditional operator, the ternary operator. (And here is a nice tutorial)

它的用法如下:

condition ? first_expression : second_expression;

基本上,如果该语句为true,则执行第一个表达式,否则,执行第二个表达式。一般来说,它是 if / else 块的小捷径,仅应用于小语句。

Basically if the statement is true, the first expression is executed, if not, the second is. Generally speaking it is a small shortcut for if/else blocks, and should be used for only small statements. Nesting the ternary operator is largely frowned upon.

因此,如果 args == null || args.Length == 0
然后 path = @ C:\GENERIC\SYSTEM\PATH ,它等于 args [1]

So if args == null || args.Length == 0 Then path = @"C:\GENERIC\SYSTEM\PATH", if not, it equals args[1]

等于您的标准 if

string path;
if(args == null || args.Length == 0)
{
   path = @"C:\GENERIC\SYSTEM\PATH";
}
else
{
   path = args[1];
}

这篇关于有人可以用简单的英语或伪代码解释三元运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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