Ear*_*rlz 14 .net c# generics struct list
我有一个List<KeyValuePair<string, othertype>>.我需要做一些事情
list.Find(x=>x.Key=="foobar")
Run Code Online (Sandbox Code Playgroud)
但是,如果列表中不存在,那么行为是什么?通常它会返回null,但结构不能为null.
Oli*_*bes 16
我的建议是FindIndex用于非可空类型
int index = list.FindIndex(x => x.Key == "foobar");
if (index >= 0) {
// found!
UseResult(list[index]);
}
Run Code Online (Sandbox Code Playgroud)
default(T)如果Find()不成功,则返回默认值.对于非可空类型,此结果无法与具有默认值的常规条目区分开.当列表可能包含常规null条目时,对于可空类型也是如此.
Jam*_*are 14
它会返回default(T),这将是相同的new KeyValuePair<string, othertype>>(),那就是默认的初始化结构.
基本上,引用类型的默认null值始终是,对于值类型(包括struct),它是默认值(0对于数值,false对于bool,a struct,每个字段默认为结构等)
所以,对于default(KeyValuePair<string, othertype>>)你来说,你会得到一个KVP,其中Key是null(默认为string)和无论如何default(othertype)(如上例所示)......
来自MSDN:
匹配指定谓词定义的条件的第一个元素(如果找到); 否则,类型T的默认值.
使用这个,如果你想检查一下,看看你是否回来了default,我建议yourResult.Key != null你查看是否有结果,或者你可以使用其他Find方法,FindIndex如Olivier建议的那样.
| 归档时间: |
|
| 查看次数: |
12694 次 |
| 最近记录: |