这的功能和好处
问题描述:
我真的不太了解这种用法,它的功能和好处是什么?
I really don''t quite understand this kind of using this, what''s its function and benefit?
public static T FirstOrDefault<T>(this IEnumerable<T> sequence, Predicate<T> test)
{
foreach (T value in sequence)
if (test(value))
return value;
return default(T);
}
答
它是一种扩展方法
http://msdn.microsoft.com/en-us/library/bb383977.aspx [ ^ ]
它允许您将自定义方法"定义为特定对象的一部分.
It''s an extension method
http://msdn.microsoft.com/en-us/library/bb383977.aspx[^]
It allows you to define ''custom methods'' as if they are part of a particular object.
这很明显.在这里,您有一个通用方法,该方法将返回您在代码中指定的对象/值的类型.因此,您的代码将是类型安全的,并且不会因为您引入的每种新类型而被迫重写代码.谓词只是一个返回true或false的函数,通过向此方法提供此函数,您可以简单地通过在谓词函数中检测到该条件并在满足条件时返回true来指定要返回什么的条件.由于该方法仅需要IEnumerableT.您几乎可以将每个对象/值的Collection传递给它,因此这使得该方法的使用非常灵活.
还有疑问吗?
问候,
曼弗雷德(Manfred)
That is quite obvious. Here you have a generic method that will return a type of object/value that you specify in your code. So your code will be typesafe and you will not be forced to rewrite the code for every new type you introduce. A predicate is just a function that returns true or false and by supplying such a function to this method you can specify the criterion of what to return simply by detecting this in the predicate function and returning true when the criterion is met. Since the method only demands an IEnumerable<T> you can pass pretty much every Collection of objects/values into it, so this makes the usage of said method very flexible.
Any doubts left?
Regards,
Manfred
这可能会有所帮助,
^ ],并阅读本文的其余部分,这可能有助于您理解它.
希望对您有所帮助:)
this might be helpful,
FirstOrDefault[^] and read the rest of the article which might help you to understand it.
Hope it helps :)