【问题标题】:What does "??" do in C#? [duplicate]什么是“??”在 C# 中做? [复制]
【发布时间】:2013-07-31 11:58:18
【问题描述】:

我在我的项目中发现了这个有趣的新代码。它有什么作用,它是如何工作的?

MemoryStream stream = null;
MemoryStream st = stream ?? new MemoryStream();

【问题讨论】:

  • 提示其称为Null Coalescing operator
  • ?? operator chaekcs if stream is null if null 然后使用 new 关键字创建新的内存流。
  • 这是混淆运算符
  • 人们的懒惰程度令人惊讶。谷歌查询“?? operator”给你一个第一次点击的答案。说真的。

标签: c# .net


【解决方案1】:

基本上这意味着如果MemoryStream stream 等于null,则创建MemoryStream st = new MemoryStream();

所以在这种情况下如下:

MemoryStream st = stream ?? new MemoryStream();

意思

MemoryStream st;

if (stream == null)
   st = new MemoryStream();
else 
   st = stream;

它被称为null coelesce operator。更多信息在这里:http://msdn.microsoft.com/en-us/library/ms173224.aspx

【讨论】:

  • 是的,它以相同的方式工作。
【解决方案2】:
A ?? B

的简写
if (A == null) 
    B
else 
    A

或更准确地说

A == null ? B : A

所以在最冗长的扩展中,您的代码相当于:

MemoryStream st;
if(stream == null)
    st = new MemoryStream();
else
    st = stream;

【讨论】:

    【解决方案3】:

    它被称为空合并运算符。见here

    表示如果stream为空,则创建一个新的MemoryStream对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-30
      • 2016-05-03
      • 1970-01-01
      • 2011-02-27
      • 2011-06-05
      • 1970-01-01
      • 2013-02-17
      相关资源
      最近更新 更多