没有启动反射器来查看差异,但是在比较Func<T, bool>
与Predicate<T>
我认为没有区别,因为它们都采用泛型参数并返回bool?
答案 0 :(得分:18)
他们共享相同的签名,但他们仍然是不同的类型。
答案 1 :(得分:17)
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");
}
}
答案 2 :(得分:2)
更灵活的Func
系列只能在.NET 3.5中运行,因此它将在功能上复制必须在之前包含的类型。
(加上名称Predicate
将预期用途传达给源代码的读者)
答案 3 :(得分:0)
即使没有泛型,您也可以拥有签名和返回类型相同的不同委托类型。例如:
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
,这不是意思是他们是“相同”类型。