[英]One-line if-else in C#
In C#, is there a one-line implementation of the following simple piece of logic ?在 C# 中,是否有以下简单逻辑的单行实现?
if (a != null)
{
b = a ;
}
else
{
// do something else;
}
Notice that in the else
I do not want to assign a different value to the variable b.请注意,在
else
我不想为变量 b 分配不同的值。
Maybe you were looking for braceless notation?也许您正在寻找无支撑符号?
if (a != null) b = a; else /*Do something else*/ ;
Please, use this sparingly and make sure the oneliner
will be readable.请谨慎使用它并确保
oneliner
可读。
不知道为什么要这样做,但这是我的看法:
((a != null) ? (Action)(() => { b = a; }) : () => { /*Do something else*/ })();
If you want to do an if / else
in a single line, you must know the structure that the code must have:如果要在一行中执行
if / else
,则必须知道代码必须具有的结构:
condition ?健康)状况 ? consequent : alternative
结果:替代
For example:例如:
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; })();
This won't change asd and it is "one-liner" but i would not recommend this over normal if else这不会改变 asd 并且它是“单线”,但我不会推荐它超过正常情况,否则
Easiest way is probably to do this:最简单的方法可能是这样做:
b = a != null ? a : b;
Syntax for this is:语法是:
someValue = condition ? newValue : someOtherValue;
If you need it to something more specific when a is null then you can do this, but it's not pretty:如果您需要在 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.