c# - 带有可空运算符的 Linq FirstOrDefault

标签 c# linq

<分区>

将 Linq 的 FirstOrDefault 与可空运算符结合使用时,出现奇怪的行为。

这是测试用例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication43
{
    class Program
    {
        static void Main( string[] args )
        {
            var x = new List<Test>( );
            x.Add( new Test { x = 1 } );
            x.Add( new Test { x = 2 } );

            var c2 = x.FirstOrDefault( e => e.x == 3 ) ?? x.FirstOrDefault( e => e.x == 1 );


            var a = x.FirstOrDefault( e => e.x == 3 );
            var b = x.FirstOrDefault( e => e.x == 1 );
            var c1 = a ?? b;
        }

        class Test
        {
            public int x;
        }
    }
}

我希望 c1 和 c2 都具有相同的值,但 c2 始终返回 null,即使是可空运算符的右侧也不是 null。

有一个类似的问题,但与值类型有关(在那种情况下doubles)

FirstOrDefault() unable to couple with ?? operator

在这种情况下,都是关于引用类型Test

最佳答案

我遇到过可空类型的调试器错误。当变量不为 null 时,调试器有时会显示 null。我相信 C# 编译器在涉及可空类型时会进行一些转换和优化。调试器有时似乎无法跟上。

使用控制台打印出值。

我将此作为答案,因为您的代码应该可以正常工作 ( and Servy has confirmed this )。这一定是调试器问题或其他一些误解。

关于c# - 带有可空运算符的 Linq FirstOrDefault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23811688/

相关文章:

c# - HttpWebRequest - 基础连接已关闭 : An unexpected error occurred on a send

c# - 如何只得到奇数参数

c# - 无法使用 mySql 在 Entity Frameworking 中使用 Decimal DataType 更新行

c# - 如何将列表分配给类模型

javascript - 当未提供内容类型 '' 应用程序/Json 时,C# [WebMethod] 未命中

c# - 如何从 javadoc 中排除某些类/包/公共(public)成员

c# - 如何在 IQueryable 对象的 LINQ 查询的 where 子句中调用方法

c# - 从字典中查找闭合值

c# - 如何用 C# 和 NAudio 覆盖两个 wav 文件?

c# - DelegateHandler 的 DI 无法正常工作