首页 文章

C#运算符`??`是如何工作的?

提问于
浏览
0

我在C#4中使用 ?? 运算符,发现了一个有趣的功能 .

这行代码 always 如果 existingObject 已经 null ,则无论 searchForObject() 返回值是否为 null (searchForObject返回非空对象,实际上它是一个linq语句而不是函数,并且如果以下语句将被简单的if构造替换)那么existingObject将被赋予一个非null对象):

existingObject = extstingObject ?? searchForObject();

有人能解释为什么吗?

这是MSDN的a link,它说:

可空类型可以包含值,也可以是未定义的 . ?? ??运算符定义将可空类型分配给非可空类型时要返回的默认值 . 如果您尝试将可空值类型分配给不可为空的值类型而不使用??运算符,您将生成编译时错误 . 如果使用强制转换,并且当前未定义可空值类型,则将抛出InvalidOperationException异常 .

关于将可空类型分配给非可空类型的部分不是我所期望的 .

The problem was deferred initialization of local variables in the debugger of Visual Studio 2010.

6 回答

  • 1

    除了我在这篇评论中所说的内容:

    您还有可能实际上没有查看正在执行的相同代码 . 它有时在Visual Studio中发生 . 重建项目,尝试清除bin文件夹,放入一些Debug.WriteLines来跟踪应用程序中的实际情况(而不是依赖IDE的Watch)等 .

    另一个问题浮出水面 - 作业后 existingObject 真的是空的吗? :)你怎么断言?

    看看我的问题(以及答案):

    Surprising CLR / JIT? behaviour - deferred initialization of a local variable

  • 2

    ?? 是简写

    if (somethingisnull)
      somethingisnull = somethingnotnull
    

    因此 searchForObject() 也必须返回null

  • 0

    ??如果操作数不为null,则返回左侧操作数;否则返回正确的操作数 .

    // ?? operator example.
        int? x = null;
        // y = x, unless x is null, in which case y = -1.
        int y = x ?? -1;
    
  • 0

    阅读:Coalescing operator - ??:Coalescing运算符是在C#2.0中添加的新运算符 . 合并算子也称为?? .

    没有?操作者

    Nullable<int> a = null; 
    Nullable<int> b = 10; 
    int c = a==null ? b.Value : a;
    

    可以替换?? ??如下所示

    Nullable<int> a = null; 
    Nullable<int> b = 10; 
    int c = a ?? b.Value;
    

    ?? is oeprate允许在第一个值为空时分配第二个值

    existingObject = extstingObject ?? searchForObject();
    

    所以在你的情况下,如果 extstingObject 为null,则获取 searchForObject() 的值并赋值给object,如果你得到null而不是第二个函数也返回null .

  • 3

    原因是其他地方错了 . 在这行代码中,如果existingObject为null,则searchForObject()的返回值将分配给existingObject .

  • 2

    这里还有其他的东西, searchForObject() 必须返回 null . 看一下下面的例子 .

    object searchForObject()
    {
        return new object();
    }
    

    通过 searchForObject() 的这个实现,我们可以这样做:

    object existingObject = null;
    existingObject = existingObject ?? searchForObject();
    

    现在如果我们测试这个就像这样:

    Console.Write("existingObject is ");
    if (existingObject == null) Console.WriteLine("null");
    else Console.WriteLine("not null");
    

    它会告诉我们 existingObject is not null . 但是,如果我们改变 searchForObject() 返回的内容:

    object searchForObject()
    {
        return null;
    }
    

    它会告诉我们 existingObject is null . 现在,最后一个测试是在我们进行第一次检查之前更改 existingObject 的值:

    object existingObject = new object();
    existingObject = existingObject ?? searchForObject();
    

    这将告诉我们 existingObject is not null .

    如果 existingObject 为null,则表示 ?? 之后的任何内容都返回null .

相关问题