关于c#:编译后,Func <T,bool>和Predicate < T >不是同一件事吗?

关于c#:编译后,Func <T,bool>和Predicate < T >不是同一件事吗?

Isn't Func and Predicate the same thing after compilation?

尚未启动反射器来查看差异,但希望在比较FuncPredicate< T >时看到完全相同的编译代码

我想没有什么区别,因为两者都采用通用参数并返回布尔值?


它们共享相同的签名,但是它们仍然是不同的类型。


Robert S.是完全正确的; 例如:-

1
2
3
4
5
6
7
8
9
10
11
12
13
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将预期的用法传达给源代码的读者)


即使没有泛型,您也可以拥有不同的委托类型,这些委托类型的签名和返回类型相同。 例如:

1
2
3
4
5
6
7
8
9
10
11
12
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);
}

在上面的示例中,两个非泛型类型具有相同的签名和返回类型。 (实际上也与PredicateFunc相同)。 但是正如我试图指出的那样,两者的"含义"是不同的。

这有点像如果我创建两个类,分别是class Car { string Color; decimal Price; }class Person { string FullName; decimal BodyMassIndex; },则仅仅是因为它们都拥有stringdecimal,这并不意味着它们是"相同"类型。


推荐阅读