Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C中的一行if-else_C# - Fatal编程技术网

C# C中的一行if-else

C# C中的一行if-else,c#,C#,在C语言中,是否有以下简单逻辑的一行实现 if (a != null) { b = a ; } else { // do something else; } 请注意,在else中,我不想为变量b指定不同的值 string asd = "asd"; string bsd = null; asd = bsd != null ? bsd : new Func<string>(() => { Console.WriteLine("Do something"); r

在C语言中,是否有以下简单逻辑的一行实现

if (a != null) 
{
    b = a ;
}
else
{
    // do something else;
}
请注意,在else中,我不想为变量b指定不同的值

string asd = "asd";
string bsd = null;

asd = bsd != null ? bsd : new Func<string>(() => { Console.WriteLine("Do something"); return asd; })();

这不会改变asd,它是一条直线,但我不推荐它超过正常值,否则我真的不知道为什么,但你可以:

if (a != null) { b = a; } else { Console.WriteLine("Welcome to the 'else' branch"); }

也许你在找无括号的符号

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

你可以做:如果一个!=空b=a;多行三值运算符如果您需要else块,它不分配给b,那么no.lines-有时意味着可读性-多行有什么问题?@L_Oste_Fa_no Defineefficient@GiladGreen为什么不呢?@Rafalon因为在这种逻辑下,整个C程序可以是一行程序:我很想编辑这个答案并正确格式化它@吉拉德格林:是的。如果您想要的不是没有新行字符,那么您应该这样要求,不要让代码没有任何新行字符。@vc74我也是:-@PeterB:是的。试试看-好的,好的:-,但是可以避免重复a吗?您可以轻松创建一个方法,如bool SetIfNotNullobject a,object b,然后调用它if!SetIfNotNulla,b/*做点别的*/@L_Oste_Fa_不,这似乎是一个有趣的难题,但我认为这样做没有任何实际的理由。当然,我很想看到一个优雅的解决方案。