2008-08-28 23 views
20

还没有解雇了反光看差异,但比较Func<T, bool>Predicate<T>编译后是不是功能<T, bool>和谓词<T>相同的东西?

我会想象没有区别,当一个希望看到完全一样的编译代码既采取通用的参数和返回布尔?

+0

@Sean - 区别在于沟通意图。当我使用谓词时,我的意思是将代码块用作“测试”,并根据测试结果采取行动。当我使用`Func `时,我只需要一个函数,它需要一个参数并返回一个布尔值。 – Gishu 2010-05-06 15:53:11

+0

可能的重复[为什么函数而不是谓词?](http://stackoverflow.com/questions/665494/why-funct-bool-instead-of-predicatet) – abatishchev 2012-04-18 13:52:31

回答

17

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

16

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"); 
    } 
} 
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; },那么仅仅是因为他们都持有stringdecimal,这并不意味着他们是“相同”的类型。

相关问题