我刚读了一篇SO 帖子,说明FirstOrDefault()返回类型会根据所选元素的值而有所不同.
例:
ICollection<String> list = new List<String>();
list.Add("bye");
int a = (from x in list where (x == "hi") select x.Length).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
在此示例中,a由于int默认值为0 ,因此将等于0.
但是,我可以.Cast<int?>()根据已经链接的帖子追加,以便null在查询返回0结果时获取.
int? a = (from x in list where ... x.Length).Cast<int?>().FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
为什么我没有得到编译时错误(或至少是一个警告),对于我的第一个例子,我使用Nullable int(int?)而不是常规int?
如果我理解正确,使用int?when执行我的第一个查询将永远不会导致值null.
das*_*ght 13
为什么我没有得到编译时错误(或至少是一个警告),对于我的第一个例子,我使用Nullable
int而不是常规int呢?如果我理解正确,使用int?执行我的第一个查询时,永远不会产生值null.
你的理解是正确的.但是,编译器不会干扰您将变量声明a为可空的愿望,因为它是一个"扩展"转换:即使从LINQ查询的赋值永远不会返回a 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
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15706 次 |
| 最近记录: |