Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 单行If条件,不带else子句_C#_If Statement_Conditional_Assignment Operator_Conditional Operator - Fatal编程技术网

C# 单行If条件,不带else子句

C# 单行If条件,不带else子句,c#,if-statement,conditional,assignment-operator,conditional-operator,C#,If Statement,Conditional,Assignment Operator,Conditional Operator,如果运算符中没有else,我们如何编写单行If条件 例如: 如果(count==0){count=2;} 我们如何才能像下面这样写上面的内容: 计数=计数==0?2 As三元运算符需要if else条件。我想在没有ternery接线员的情况下做这件事。C#中是否有操作员可用 谢谢 count = count == 0 ? 2 : count; 或者为了更有趣: using System; public class Program { public stat

如果运算符中没有else,我们如何编写单行If条件

例如:

如果(count==0){count=2;}

我们如何才能像下面这样写上面的内容:

计数=计数==0?2

As三元运算符需要if else条件。我想在没有ternery接线员的情况下做这件事。C#中是否有操作员可用

谢谢

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);
        }
    }
}

您不需要将
else
if
配对;您可以自己使用它:

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;
}

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

int? count = null; // initialization

// ... later

count = count ?? 2;

你不能。只需使用一个
if
语句即可。您开始使用的
if(count==0){count=2;}
语句是“没有
else
的单行
if
语句”。这有什么问题,或者三元运算符有什么问题?这些是C#提供的实现方法,所以这就是您使用的方法。可能重复或为什么不使用三元运算符?这绝对需要什么?