【问题标题】:How to compact if operator for this statement in Unity C#如何在 Unity C# 中为该语句压缩 if 运算符
【发布时间】:2016-08-05 20:03:55
【问题描述】:

在“Unity”中我们经常调试到控制台。

public bool printInConsole;

void Start()
{
    if ( printInConsole ) Debug.Log("Starting and printing...");
}

我想使用 compact 调用这个 Unity 函数?三元运算符。
如何使用 C# 在 Unity 中为此编写语句?

【问题讨论】:

  • 你的“假”案例是什么?
  • 你还有别的吗?
  • 不在控制台中显示。不,我没有 else
  • 如果你没有 else 情况,那么你不需要三元运算符。也许你应该多解释一下你想要达到的目标......
  • 不仅没有别的,而且Debug.Log大概就是void吧?所以表达式也没有任何返回值。

标签: c# debugging if-statement unity3d ternary-operator


【解决方案1】:

在您的情况下,因为您只想在满足条件时打印,所以您可以使用 if 块并且不需要使用三元运算符。

if ( printInConsole ) 
   Debug.Log("Starting and printing..."); 

【讨论】:

    【解决方案2】:

    如果您有几件事要记录,并且只想避免“if / log”循环,则可以创建一个方法:

    private void LogIt(string msg)
    {
        if (printInConsole)
            Debug.Log(msg);
    }
    

    然后,您只需在每次想要记录某些内容时致电 LogIt()

    【讨论】:

    • 那肯定更干了。
    【解决方案3】:

    TLDR 使用 if:

    if ( printInConsole ) Debug.Log("Starting and printing..."); 
    

    C#中三元表达式的语法如下:

    condition ? first_expression : second_expression;
    

    在您的场景中,不能使用三元运算符,因为:

    1. 它需要两个表达式:一个用于conditiontrue(first_expression) 的情况,另一个用于false(second_expression)。
    2. 三元运算符表达式必须返回一个值,Debug.Log() 返回void

    您可以发明一些疯狂的方法来将您的逻辑拟合到三元运算符中,例如将 Debug.log() 调用包装在 Action 委托中,但这将是浪费,因为三元运算符的全部意义在于使您的代码更简单...

    【讨论】:

      【解决方案4】:

      不,没有办法使 if 语句比以下更紧凑:

      if ( printInConsole ) Debug.Log("Starting and printing...");
      

      正如 "Rahul" 指出的那样,一种更好的视觉方式更具可读性:

      if ( printInConsole ) 
         Debug.Log( "Starting and printing..." );
      

      正如“Genos”提到的那样,使用 C# 紧凑三元运算符是不正确的,例如:

      printInConsole ? Debug.Log("Starting and printing...");
      

      因为它需要第二个 else 表达式。

      可以在函数内部做,但结果不是更紧凑、更简单、更易读。:

      Debug.Log(printInConsole ? "Running and printing..." : "\n");
      

      "itsme86" 而我的常规解决方案是创建一个特定的紧凑函数方法。这样调用函数就更紧凑了。

      Mss("Starting and printing..." );
      

      在我的例子中,完整的 Unity 代码示例是:

      public bool printInConsole;
      
      void Start()
      {
          Mss("Starting and printing..." );
      }
      
      private void Mss(string consoleMessage)
      {
          if (printInConsole)
              Debug.Log(consoleMessage + "\n");
      }
      

      另一种解决方案是为键盘按钮分配一个自定义宏以打印出来:

      if ( printInConsole ) 
         Debug.Log( "" + "\n");
      

      由于我不是英语,请您改进我的回答。

      【讨论】:

        【解决方案5】:
        if(printInConsole)?Debug.Log("Starting and printing..."): _you_else_condition_
        

        【讨论】:

        • 您正在将 VB.NET 三元运算符语法与 C# 混合使用。并且,OP 明确表示,就像 7 分钟前一样,他没有“其他”条件。并且Debug.Log 不返回任何内容,因此无法编译。
        • No this answer给出错误信息:error CS1525: Unexpected symbol `?'
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-26
        • 2019-05-06
        • 1970-01-01
        • 1970-01-01
        • 2012-12-28
        相关资源
        最近更新 更多