gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:21:59 24 4
gpt4 key购买 nike

<分区>

将 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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com