c# - 我可以将三元运算符与两个函数一起使用,每个函数都返回 void 吗?

标签 c# if-statement methods inline void

<分区>

在 C# 中可以使用没有值的 if 内联条件,换句话说返回 void?

public void FuncReturningVoid ()
{
    return;
}

public void AnotherFuncReturningVoid()
{
    return;
}

public void Test ()
{
    int a = 1;
    int b = 2;

    // I whish I could to do this:
    a == b ? FuncReturningVoid() : AnotherFuncReturningVoid();

    //would be the same...
    if (a == b)
    {
        FuncReturningVoid();
    }
    else
    {
        AnotherFuncReturningVoid();
    }
}

最佳答案

没有。不可能。这是编译错误:

  • 只有assignment、call、increment、decrement、await、new对象表达式可以作为语句使用
  • 无法确定条件表达式的类型,因为“void”和“void”之间没有隐式转换

关于c# - 我可以将三元运算符与两个函数一起使用,每个函数都返回 void 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24082901/

相关文章:

c# - 如果字符串包含特定字符则数据触发

c# - ASP.NET MVC,创建将多个对象返回到 View 的 View 方法

Python 猜谜游戏——if vs while

scala - 在 Scala 中省略括号

java - 如何使用 for 循环将返回对象数组复制到另一个数组

c# - 判断小数是否大于四位

c# - #region/#endregion 与子函数?

python - 对象具有值(value)但似乎不存在?

javascript - 如何向已经包含 .map 和 .filter 的箭头函数添加 if 、 else if 和 else 条件?

java - 如何在一个类中做一个方法,在另一个类中操作变量?