[英]Can this boolean if-else statement be turned into a one-line expression?
[英]One-line if-else in C#
在 C# 中,是否有以下簡單邏輯的單行實現?
if (a != null)
{
b = a ;
}
else
{
// do something else;
}
請注意,在else
我不想為變量 b 分配不同的值。
也許您正在尋找無支撐符號?
if (a != null) b = a; else /*Do something else*/ ;
請謹慎使用它並確保oneliner
可讀。
不知道為什么要這樣做,但這是我的看法:
((a != null) ? (Action)(() => { b = a; }) : () => { /*Do something else*/ })();
如果要在一行中執行if / else
,則必須知道代碼必須具有的結構:
健康)狀況 ? 結果:替代
例如:
string A = "test";
Console.WriteLine(String.IsNullOrEmpty(A) ? "Yes" : "No");
//Result = No
string B = "";
Console.WriteLine(String.IsNullOrEmpty(B) ? "Yes" : "No");
//Result = Yes
我真的不知道為什么,但是是的,您可以:
if (a != null) { b = a; } else { Console.WriteLine("Welcome to the 'else' branch"); }
string asd = "asd";
string bsd = null;
asd = bsd != null ? bsd : new Func<string>(() => { Console.WriteLine("Do something"); return asd; })();
這不會改變 asd 並且它是“單線”,但我不會推薦它超過正常情況,否則
最簡單的方法可能是這樣做:
b = a != null ? a : b;
語法是:
someValue = condition ? newValue : someOtherValue;
如果您需要在 a 為空時更具體的東西,那么您可以這樣做,但它並不漂亮:
public static void Main()
{
int? a = null;
int b = 0;
b = a != null ? a.Value : yeet(b);
System.Console.WriteLine(b);
}
public static int yeet(int b){
System.Console.WriteLine("yeet");
return b;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.