【问题标题】:Isn't Func<T, bool> and Predicate<T> the same thing after compilation?编译后的 Func<T, bool> 和 Predicate<T> 不是一回事吗?
【发布时间】:2008-08-28 16:17:52
【问题描述】:

尚未启动反射器来查看差异,但在比较 Func&lt;T, bool&gt;Predicate&lt;T&gt; 时,希望看到完全相同的编译代码

我想两者都采用泛型参数并返回 bool 没有区别?

【问题讨论】:

  • @Sean - 不同之处在于传达意图。当我使用谓词时,我的意思是将代码块用作“测试”并根据测试结果采取行动。当我使用Func&lt;T, bool&gt; 时,我只需要授权一个接受参数并返回布尔值的函数。

标签: c# .net predicate func


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    Robert 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");
      }
    }
    

    【讨论】:

      【解决方案3】:

      更灵活的Func 系列仅出现在 .NET 3.5 中,因此它会在功能上复制之前必须包含的类型。

      (加上名称Predicate 将预期用途传达给源代码的读者)

      【讨论】:

        【解决方案4】:

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

        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&lt;string&gt;Func&lt;string, bool&gt; 相同)。但正如我试图指出的,两者的“意义”是不同的。

        这有点像如果我创建两个类,class Car { string Color; decimal Price; }class Person { string FullName; decimal BodyMassIndex; },那么仅仅因为它们都拥有一个 string 和一个 decimal,这并不意味着它们是“相同的”输入。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-10-14
          • 2012-04-05
          • 1970-01-01
          • 2010-10-18
          • 1970-01-01
          相关资源
          最近更新 更多