使用C#三元运算符

时间:2016-08-23 19:09:17

标签: c# operator-keyword ternary

可能是一个简单的语法问题。这是对控制台程序的尝试,该程序读取通过用户输入接收的字符串的长度。如果长度大于144,则通知用户字符串长度太长,否则输入的字符串只输出到控制台。

string input = Console.ReadLine();
(input.Length > 144) ? Console.WriteLine("The message is too long"); : Console.WriteLine(input);
Console.ReadLine();

在第2行获取当前状态的语法错误。我是否缺少括号?

2 个答案:

答案 0 :(得分:8)

尝试:

Console.WriteLine((input.Length > 144) ? "The message is too long" : input);

您需要使用运算符的返回值,否则会收到编译时错误Only assignment, call, increment, decrement, and new object expressions can be used as a statement

这些其他答案都不会编译,我不确定每个人都会得到什么。

答案 1 :(得分:-3)

你有一个额外的分号。 三元表达式是ONE表达式,因此它的末尾只有一个分号。

(input.Length > 144) ? Console.WriteLine("The message is too long") /*No Semi Here*/ : Console.WriteLine(input);

我相信在C#中(与C和C ++不同),三元表达式不能单独存在 的结果必须 才能分配或使用。

整体表达式必须具有值,但Console.WriteLine不返回值(返回类型void)。您不能使用评估为void的三元组。

您已尝试将三元作为独立声明使用,这是不合法的。

相关问题