Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.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#_.net_Asp.net - Fatal编程技术网

什么是'';用C#表示什么意思?

什么是'';用C#表示什么意思?,c#,.net,asp.net,C#,.net,Asp.net,可能重复: 我试图理解这句话的含义:“?”是什么意思? 此som类型是否为if station string cookieKey = "SearchDisplayType" + key ?? ""; 是的。嗯,不是真的 事实上,是的。还有,还有,举几个例子。我使用万能的谷歌搜索它们,因为SO没有搜索答案的功能(正确吗?),因此很难找到此类问题的重复项。好吧,以后用这个作为参考 它被称为空合并运算符。基本上和我的一样 int? nullableDemoInteger; // ... int s

可能重复:

我试图理解这句话的含义:“?”是什么意思? 此som类型是否为if station

string cookieKey = "SearchDisplayType" + key ?? "";
是的。嗯,不是真的

事实上,是的。还有,还有,举几个例子。我使用万能的谷歌搜索它们,因为SO没有搜索答案的功能(正确吗?),因此很难找到此类问题的重复项。好吧,以后用这个作为参考

它被称为空合并运算符。基本上和我的一样

int? nullableDemoInteger;
// ...
int someValue = nullableDemoInteger ?? -1;
// basically same as
int someValue = nullableDemoInteger.HasValue ? nullableDemoInteger.Value : -1;
// basically same as
int someValue;
if(nullableDemoInteger.HasValue)
    someValue = nullableDemoInteger.Value;
else
    someValue = -1;

它被称为空合并运算符。 请参阅:

是操作员。这意味着,如果第一部分有值,则返回该值,否则返回第二部分

例如:

或者一些实际代码:

IEnumerable<Customer> customers = GetCustomers();
IList<Customer> customerList = customers as IList<Customer> ?? 
    customers.ToList();

与在一行内使用空合并运算符相比,这是大量的代码。

这是一个检查值是否为空并在
??
之后返回值(如果为空)。

是空合并运算符

这意味着,如果
key
不为null,它将使用key的值,如果key为null,它将使用值

。在这种情况下,它大致相当于:

string cookieKey;
string temp = "SearchDisplayType" + key;
if (temp == null)
    cookieKey = "";
else
    cookieKey = temp;
string cookieKey = "SearchDisplayType" + key;
而且,由于
“SearchDisplayType”+key
永远不能为
null
,这完全等同于:

string cookieKey;
string temp = "SearchDisplayType" + key;
if (temp == null)
    cookieKey = "";
else
    cookieKey = temp;
string cookieKey = "SearchDisplayType" + key;
???是的

从MSDN:

这个??运算符称为 使用空合并运算符和 要定义的默认值,请执行以下操作: 可为空的值类型以及 引用类型。它返回 如果左操作数不为空,则为左操作数; 否则它将返回正确的 操作数

但是,请注意,在您的例子中,表达式的左侧部分不能为null,因为它是字符串常量与变量的串联。如果键为null,则“SearchDisplayType”+键的计算结果为“SearchDisplayType”

我想你声明的意图可以通过以下方式实现:

string cookieKey = key==null ? "" : "SearchDisplayType"+key;

使用此代码,如果key为null,则cookieKey设置为空字符串;否则,如果可以在上搜索“?”,则设置为“SearchDisplayType”+key

的串联,因此这将符合以下内容的副本,例如:-(1.启动C#.2.
3.利润!注意,由于运算符的优先级,运算符“”应用于整个语句:“SearchDisplayType”+键,该键始终不为空是的,您是对的,我们已经讨论过了。注意:始终使用(偏执)使用空合并运算符…+1。比我快。到目前为止,唯一的答案是提到
+
的优先级,并且在OP的示例中它是多余的。错误。如果(key==null)不是If(“SearchDisplayType”+key==null)。@Goran:不,LukeH是正确的。也许这不是直观的,但要测试一下。@Goran:你为什么不在否决投票前试一试呢?我试过了。智力?y=null;字符串x=“测试”+y??""; 生成“test”not“。只有一点->您不能执行
var foo=null@Yossarian-是的,很好,但这只是伪代码。我更改了它以避免混淆。@Yossarian-您可以执行
var foo=(object)null
var foo=(SomeClass)null这将有助于保持变量名对齐,代码易于阅读。+1的最佳用法??是可为空的类型吗