我以前认为List <T>被认为是危险的.我的观点是,我认为默认(T)不是一个安全的返回值!许多其他人也这么认为考虑以下问题:
List<int> evens = new List<int> { 0, 2, 4, 6, , 8};
var evenGreaterThan10 = evens.Find(c=> c > 10);
// evenGreaterThan10 = 0 #WTF
Run Code Online (Sandbox Code Playgroud)
值类型的默认值(T)为0,因此返回0是goona以上代码段!
我不喜欢这个,所以我添加了一个名为TryFind的扩展方法,它返回一个布尔值并接受除Predicate之外的输出参数,类似于着名的TryParse方法.
编辑:
这是我的TryFind扩展方法:
public static bool TryFind<T>(this List<T> list, Predicate<T> predicate, out T output)
{
int index = list.FindIndex(predicate);
if (index != -1)
{
output = list[index];
return true;
}
output = default(T);
return false;
}
Run Code Online (Sandbox Code Playgroud)
你有什么办法在通用名单上查找?
Tom*_*han 15
我不.我做.Where()
evens.Where(n => n > 10); // returns empty collection
evens.Where(n => n > 10).First(); // throws exception
evens.Where(n => n > 10).FirstOrDefault(); // returns 0
Run Code Online (Sandbox Code Playgroud)
第一种情况只返回一个集合,所以我可以简单地检查计数是否大于0来知道是否有任何匹配.
当使用第二个时,我在一个try/catch块中包装,该块以规范方式处理InvalidOperationException以处理空集合的情况,并且只需重新抛出(冒泡)所有其他异常.这是我使用最少的一个,因为我不喜欢编写try/catch语句,如果我可以避免它.
在第三种情况下,我没关系,当没有匹配时代码返回默认值(0) - 毕竟,我明确地说"让我得到第一个或默认值".因此,我可以阅读代码并理解为什么如果我遇到问题就会发生这种情况.
更新:
对于.NET 2.0用户,我不建议在评论中建议的hack.它违反了.NET的许可协议,任何人都不会支持它.
相反,我认为有两种方法:
Upgrade. Most of the stuff that runs on 2.0 will run (more or less) unchanged on 3.5. And there is so much in 3.5 (not just LINQ) that is really worth the effort of upgrading to have it available. Since there is a new CLR runtime version for 4.0, there are more breaking changes between 2.0 and 4.0 than between 2.0 and 3.5, but if possible I'd recommend upgrading all the way to 4.0. There's really no good reason to be sitting around writing new code in a version of a framework that has had 3 major releases (yes, I count both 3.0, 3.5 and 4.0 as major...) since the one you're using.
找到解决Find
问题的方法.我建议FindIndex
你只是像你一样使用,因为当找不到任何内容时返回的-1永远不会模糊,或者FindIndex
像你一样实现某些东西.我不喜欢这种out
语法,但在我编写一个不使用它的实现之前,我需要一些关于你什么时候找不到的东西的输入.
在那之前,TryFind
可以认为是好的,因为它与.NET中的先前功能一致Integer.TryParse
.并且你确实得到了一个很好的方法来处理发现的事情
List<Something> stuff = GetListOfStuff();
Something thing;
if (stuff.TryFind(t => t.IsCool, thing)) {
// do stuff that's good. thing is the stuff you're looking for.
}
else
{
// let the user know that the world sucks.
}
Run Code Online (Sandbox Code Playgroud)而不是Find
你可以使用FindIndex
.它返回找到的元素的索引,或者-1
是否找不到元素.
http://msdn.microsoft.com/en-us/library/x1xzf2ca%28v=VS.80%29.aspx
归档时间: |
|
查看次数: |
11215 次 |
最近记录: |