簡體   English   中英

你如何讓“if”語句“什么都不做”?

[英]How do you make an 'if' statement do "nothing"?

這是我的代碼示例。 我需要最后一個if什么都不做,否則做點什么。

if (daPilot.Gas > 0)
    ;
else
    daPilot.failMessage3();

你已經做到了。 恭喜。

當然遠不如混亂的設計是只是沒有條件,然后有一個if沒有else

if (daPilot.Gas > 0) 
{
    // nothing
}                        
else
{
    daPilot.failMessage3();
}

或者更簡單地說,

if (daPilot.Gas <= 0) 
{        
    daPilot.failMessage3();
}

兩種方式:

  1. 空卷發:

     if (condition) { } else { method(); }
  2. 意識到您可以簡單地反轉條件:

     if (!condition) method();

只需反轉if條件並僅聲明true部分:

if (daPilot.Gas <= 0)
    daPilot.failMessage3();

無論如何,您總是可以在需要時聲明一個空體: { }
例如:

while (condition)
{
}

設定什么都不做的條件是沒有意義的。 你應該這樣做。

if (daPilot.Gas <= 0)
    daPilot.failMessage3();

反轉if

if (daPilot.Gas <= 0) daPilot.failMessage3();

你可以反轉if ,試試這個:

if (daPilot.Gas <= 0)
{
    daPilot.failMessage3();
}

如果你真的想讓它什么都不做

       {
            if (daPilot.Gas > 0)
            {
            }
            else
            {
              daPilot.failMessage3();
            }
        }

讓我們使用'!' 運營商喜歡:

if (!(daPilot.Gas > 0))
      daPilot.failMessage3();

或使用額外的變量:

var isGasGreaterToZero = daPilot.Gas > 0; /*true or false*/

if(!isGasGreaterToZero)
    daPilot.failMessage3();

在這兩種情況下,如果daPilot.Gas大於零 (0),什么都不會發生!

我喜歡下面的代碼 - 它使用零或一行,但需要擴展到樹線

#pragma warning disable CS0642 // Possible mistaken empty statement
                ;
#pragma warning restore CS0642 // Possible mistaken empty statement

還可以在兩行中使用{ }或在if語句中使用零行:

if (...) { }

在 if 語句中寫一些什么都不做的代碼:

如果(daPilot.Gas > 0)var S = true;

我同意這里的其他答案。 最好扭轉條件,如果您不想這樣做,最好使用空塊{ /* nothing */ }

但是現在,假設您正在尋找以下解決方案:

  1. 不逆轉條件。
  2. 不使用代碼塊。
  3. 不生成警告或錯誤或禁止此類消息。
  4. 對生成的編譯器代碼影響最小。

你怎么能這樣做?

答案:使用_ = 0

我想出了以下在 .NET 3 和 5 中有效的代碼示例:

if (new Random().Next(2) == 0)
    _ = 0; // do nothing
else
    Console.WriteLine("Do Something");

如果您檢查編譯器生成的未優化的 IL 代碼,您會看到該指令已被nop替換。

在此處輸入圖片說明

通過優化,條件已被編譯器反轉,然后條件的一部分被完全優化掉。

在此處輸入圖片說明

結論: _ = 0; 符合要求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM