简体   繁体   English

使用C#三元运算符

[英]Using C# Ternary Operator

Probably a simple syntax problem. 可能是一个简单的语法问题。 This is an attempt at a console program that reads the length of a string that is received via user input. 这是尝试在控制台程序中读取通过用户输入接收的字符串的长度。 If the length is greater than 144, the user is notified that the string length is too long, otherwise the string inputted is just output to the console. 如果长度大于144,则会通知用户字符串长度太长,否则将输入的字符串仅输出到控制台。

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

Getting syntax errors in the present state on line 2. Am I missing parentheses? 在第2行的当前状态下获取语法错误。我是否缺少括号?

try: 尝试:

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

you need to use the return value of the operator, or receive a compile-time error Only assignment, call, increment, decrement, and new object expressions can be used as a statement . 您需要使用运算符的返回值,或者接收到编译时错误。 Only assignment, call, increment, decrement, and new object expressions can be used as a statement

None of these other answers will compile, I'm not sure what everyone is getting at. 这些其他答案都无法编译,我不确定每个人都在做什么。

You have an extra semi-colon. 您有多余的分号。 The ternary expression is ONE expression, so it only has one semi-colon at the end of it. 三元表达式是ONE表达式,因此它的末尾只有一个分号。

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

I believe that in C# (unlike C and C++), a ternary expression cannot be standalone. 我相信在C#中(与C和C ++不同),三元表达式不能是独立的。
The result of it must be assigned or used. 必须分配或使用它的结果。

The expression overall must have a value, but Console.WriteLine does not return a value (return type void ). 表达式整体必须具有一个值,但是Console.WriteLine不会返回值(返回类型void )。 You cannot have a ternary that evaluates to type void . 您不能有一个三元运算符,其结果类型为void

You have tried to use the ternary as a standalone statement, which is not legal. 您试图将三进制用作独立的语句,这是不合法的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM