使用C#三元运算符

Ale*_*rds 0 c# ternary operator-keyword

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

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

在第2行获取当前状态的语法错误.我错过了括号吗?

Jon*_*lis 8

尝试:

Console.WriteLine((input.Length > 144) ? "The message is too long" : input);
Run Code Online (Sandbox Code Playgroud)

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

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