gpt4 book ai didi

c# - Int 和 Int 的 FirstOrDefault 行为?

转载 作者:可可西里 更新时间:2023-11-01 03:10:10 25 4
gpt4 key购买 nike

我刚刚读了一个 SO post这解释了 FirstOrDefault()的返回类型将根据所选元素的值而变化。

例子:

ICollection<String> list = new List<String>();
list.Add("bye");

int a = (from x in list where (x == "hi") select x.Length).FirstOrDefault();

在这个例子中,a将等于 0,因为 int默认值为 0。

但是,我可以附加 .Cast<int?>()根据已经链接的帖子以获得null当查询返回 0 个结果时。

int? a = (from x in list where ... x.Length).Cast<int?>().FirstOrDefault();

在我的第一个示例中,当我使用 Nullable int ( int? ) 而不是常规 int 时,为什么我没有收到编译时错误(或至少是警告) ?

如果我理解正确,使用 int?当执行我的第一个查询时,从不会得到 null 的值.

最佳答案

Why don't I get a compile-time error (or at least a warning) when, for my first example, I use a Nullable int rather than a regular int then? If I understand correctly, using a int? when performing my first query will never result in a value of null.

你的理解是正确的。但是,编译器不会干扰您将变量 a 声明为可为 null 的愿望,因为这是一个“扩大”转换:即使来自 LINQ 查询的赋值永远不会返回 null,您可能对下面的同一变量有其他用途:

int? a = (from x in list where (x == "hi") select x.Length).FirstOrDefault();
// Do something with `a`, which will not be null
...
a = null;
if (someCondition) {
a = someNotNullValue();
}
// Here, a may or may not be null
...

关于c# - Int 和 Int 的 FirstOrDefault 行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17775030/

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