编译后,Func<T, bool> 和 Predicate<T> 不是相同的东西吗?

21
我还没有查看反编译器来比较这两者之间的区别,但是当比较“Func<T, bool>”和“Predicate<T>”时,是否预期会看到完全相同的编译代码呢?我认为没有任何区别,因为它们都采用了通用参数并返回布尔值。

@Sean - 区别在于传达意图。当我使用谓词时,我的意思是将代码块用作“测试”,并根据测试结果采取行动。当我使用 Func<T, bool> 时,我只需要强制执行一个函数,该函数接受一个参数并返回一个布尔值。 - Gishu
可能是为什么使用Func<T,bool>而不是Predicate<T>?的重复问题。 - abatishchev
4个回答

18

它们具有相同的标识,但仍然是不同类型。


17

罗伯特·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");
  }
}

2
更加灵活的Func类家族在.NET 3.5才出现,因此它们在功能上会与早期必须包含的类型发生重复。
(此外,名称Predicate向源代码的读者传达了预期的用途)

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,这并不意味着它们是“相同”的类型。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接