【问题标题】:Single line If condition without else clause [duplicate]没有 else 子句的单行 If 条件 [重复]
【发布时间】:2019-09-14 02:39:18
【问题描述】:

我们如何在运算符中写一个没有 else 的单行 If 条件?

例子:

如果(计数==0){计数=2; }

我们如何在上面写如下:

count=count==0?2;

作为三元运算符需要 if else 条件。我想在没有三元运算符的情况下做到这一点。 C#中是否有可用的运算符?

谢谢。

【问题讨论】:

标签: c# if-statement conditional assignment-operator conditional-operator


【解决方案1】:

您不需要将elseif 配对;你可以单独使用它:

if (count == 0)
        count = 2;

如果语法不符合您的喜好,可以用多种方式编写:

if (count == 0) count = 2;

if (count == 0) { count = 2; }

if (count == 0) {
    count = 2;
}

if (count == 0)
{
    count = 2;
}

正如另一张海报指出的那样,您可以使用可空 int 并初始化为 null 以与空合并运算符进行二进制交互:

int? count = null; // initialization

// ... later

count = count ?? 2;

【讨论】:

    【解决方案2】:
    count = count == 0 ? 2 : count;
    

    或者为了更多乐趣:

    using System;               
    public class Program
    {
        public static void Main()
        {
            foreach(int x in System.Linq.Enumerable.Range(-5, 10))
            {
                int count = x;
                bool y = count == 0 && (0 == count++ - count++);
                Console.WriteLine(count);
            }
        }
    }
    

    【讨论】:

    • 为什么不用三元运算符?这绝对需要什么?
    猜你喜欢
    • 1970-01-01
    • 2020-12-10
    • 2021-11-30
    • 2021-12-21
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    相关资源
    最近更新 更多