我还没有查看反编译器来比较这两者之间的区别,但是当比较“Func<T, bool>”和“Predicate<T>”时,是否预期会看到完全相同的编译代码呢?我认为没有任何区别,因为它们都采用了通用参数并返回布尔值。
它们具有相同的标识,但仍然是不同类型。
罗伯特·S. 是完全正确的;例如:
class A {
static void Main() {
Func<int, bool> func = i => i > 100;
Predicate<int> pred = i => i > 100;
Test<int>(pred, 150);
Test<int>(func, 150); // Error
}
static void Test<T>(Predicate<T> pred, T val) {
Console.WriteLine(pred(val) ? "true" : "false");
}
}
Func
类家族在.NET 3.5才出现,因此它们在功能上会与早期必须包含的类型发生重复。Predicate
向源代码的读者传达了预期的用途)namespace N
{
// Represents a method that takes in a string and checks to see
// if this string has some predicate (i.e. meets some criteria)
// or not.
internal delegate bool StringPredicate(string stringToTest);
// Represents a method that takes in a string representing a
// yes/no or true/false value and returns the boolean value which
// corresponds to this string
internal delegate bool BooleanParser(string stringToConvert);
}
Predicate<string>
和 Func<string, bool>
相同)。但正如我试图表明的那样,这两者的“含义”是不同的。class Car { string Color; decimal Price; }
和 class Person { string FullName; decimal BodyMassIndex; }
,然后仅仅因为它们都包含一个 string
和一个 decimal
,这并不意味着它们是“相同”的类型。
Func<T, bool>
时,我只需要强制执行一个函数,该函数接受一个参数并返回一个布尔值。 - Gishu