2008-08-28 6 views
20

は違いを見て反射鏡を解雇いないが、違いはありませんFunc<T, bool>対私は想像Predicate<T>コンパイル後にFunc <T, bool>と述語<T>が同じことはありませんか?

を比較するときに1がまったく同じコンパイルされたコードを見ることを期待するの両方は、一般的なパラメータを取り、ブール値を返すよう?

+0

@Sean - 違いは、コミュニケーションの意図にあります。述語を使うときは、コードのブロックを「テスト」として使用し、テスト結果に基づいてアクションを実行することを意味します。 'Func 'を使うときは、パラメータをとり、boolを返す関数を指定する必要があります。 – Gishu

+0

可能性のある複製[なぜFunc の代わりに?](http://stackoverflow.com/questions/665494/why-funct-bool-instead-of-predicatet) – abatishchev

答えて

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

例によって違いを示す良い方法 – RichardOD

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

上記の例では、2つの非ジェネリック型は同じシグネチャと戻り値の型を持っています。 (実際はPredicate<string>Func<string, bool>と同じです)。しかし、私が示すように、2つの "意味"は異なっています。

これは、それらの両方は、彼らが「同じ」タイプだという意味ではありませんstringdecimalを保持するという理由だけで、その後、やや私は二つのクラス、class Car { string Color; decimal Price; }class Person { string FullName; decimal BodyMassIndex; }を作る場合のようなものです。

関連する問題