【问题标题】:Is there a way to use ? : notation without assignment / with methods returning void [duplicate]有没有办法使用? :没有赋值的符号/带有返回void的方法[重复]
【发布时间】:2013-06-22 02:03:12
【问题描述】:

有没有办法使用? : c# 中的表示法,在 ? 之后没有分配表达式的结果,甚至没有分配表达式的结果运算符,不返回任何值。

例如我想运行类似的东西

(1=1) ? errorProvider.SetError(control,"Message") : DoNothing();

expression? DoSomething (): DoSomethingElese()

其中 DoSomething 和 DoSomethingElse 返回的类型为 void。

【问题讨论】:

  • 为什么?您可以随时使用if (expression) DoSomething(); else DoSomethingElese();
  • 是的,但是我在徘徊是否有办法破解它。
  • 这是另一种将代码缩短为几行的尝试吗?

标签: c# .net conditional-operator


【解决方案1】:

没有。三元运算符的全部意义在于它返回了一些东西。换句话说:表达式必须有一个返回类型(void 除外)。在这种情况下,您只需要使用if/else 构造即可。

【讨论】:

    【解决方案2】:

    没有。

    ?: 根据boolean 条件返回一个值。你不能使用void 表达。

    只需使用if

       if (expression) {
            DoSomething();
       } else {
            DoSomethingElse();
       }
    

    http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.110).aspx

    【讨论】:

      【解决方案3】:

      正如其他人所说,您不能 - If/Else 将是正确的选择。不过,在您的示例中,您可以执行以下操作:

      errorProvider.SetError(control, SomeCondition ? "Message" : string.Empty) 
      

      【讨论】:

        【解决方案4】:

        你可以得到最接近的方法是扩展布尔类型:

        public static void IIF(this bool condition, Action doWhenTrue, Action doWhenFalse)
        {
            if (condition)
                doWhenTrue();
            else
                doWhenFalse();
        }
        

        然后你赢得了一个单行:

        (1 == 1).IIF(() => DoSomething(), () => DoSomethingElse());
        

        【讨论】:

          猜你喜欢
          • 2020-01-16
          • 1970-01-01
          • 2017-01-27
          • 2013-07-02
          • 1970-01-01
          • 1970-01-01
          • 2017-07-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多