简体   繁体   English

对此感到困惑? c#中的运算符

[英]Confused about the ? operator in c#

I want to make it so that if the value of subs is not "" then the ULs go before and after it and into the variable sL. 我想这样做,如果subs的值不是“”,那么UL在它之前和之后进入变量sL。 If subs is "" then sL get the value "" 如果subs是“”,则sL得到值“”

var sL = (subs != "") ? "<ul>" + subs + "</ul>" : "";

But it doesn't seem to work. 但它似乎没有用。

Is my format correct? 我的格式是否正确?

When in doubt, add more brackets: 如有疑问,请添加更多括号:

var sL = subs != "" ? ("<ul>" + subs + "</ul>") : "";

However, your code should work fine already; 但是,您的代码应该已经正常工作; that syntax is fine. 那句法很好。

Susan, your code is correct and it works. 苏珊,你的代码是正确的,它的工作原理。 I just tested in LinqPad. 我刚刚在LinqPad中测试过。 Perhaps your ss variable is null and not empty. 也许你的ss变量是null而不是空的。 I recommend you change your line to: 我建议你将你的行改为:

var sL = !string.IsNullOrEmply(subs) ? "<ul>" + subs + "</ul>" : "";

This should be the same to this: 这应该与此相同:

if (subs != "")
{
    sL = "<ul>" + subs + "</ul>";
}
else
{
    sL = "";
}

If this is what you are aiming for, then I would surround the "<ul>" + subs + "</ul>" in brackets, just to be sure the compiler understands what you want. 如果这是你的目标,那么我会在括号中包围"<ul>" + subs + "</ul>" ,只是为了确保编译器能够理解你想要的东西。

I copy-pasta'd your code and it worked fine on my machine. 我复制了你的代码,它在我的机器上运行良好。

Perhaps the problem is somewhere else? 也许问题出在其他地方?

As an aside, rather use string.IsNullOrEmpty over = "" string.IsNullOrEmpty ,而是使用string.IsNullOrEmpty over = ""

var sL = !string.IsNullOrEmpty(subs) ? "<ul>" + subs + "</ul>" : string.Empty;

没人提到的另一个选择是使用string.Concat而不是+ ,如下所示:

var sL = (subs != "") ? string.Concat("<ul>", subs, "</ul>") : "";

If subs is "" then sL becomes "" as well. 如果subs是“”,则sL也变为“”。 You are just using a shorthand variant of if. 您只是使用if的简写变体。 What you have written is exactly the same as 你所写的内容完全相同

string sL;
if (subs != ""){
  sL = "<ul>" + subs + "</ul>";
}else{
  sL = "";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM