Pregunta

No he encendido el reflector para ver la diferencia, pero uno esperaría ver exactamente el mismo código compilado al comparar. Func<T, bool> vs. Predicate<T>

Me imagino que no hay diferencia ya que ambos toman un parámetro genérico y devuelven bool.

¿Fue útil?

Solución

Comparten la misma firma, pero siguen siendo tipos diferentes.

Otros consejos

Roberto S.es completamente correcto;Por ejemplo:-

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

Cuanto más flexible Func La familia solo llegó a .NET 3.5, por lo que duplicará funcionalmente los tipos que tuvieron que incluirse anteriormente por necesidad.

(Más el nombre Predicate comunica el uso previsto a los lectores del código fuente)

Incluso sin genéricos, puede tener diferentes tipos de delegados que sean idénticos en firmas y tipos de devolución.Por ejemplo:

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

En el ejemplo anterior, los dos tipos no genéricos tienen la misma firma y tipo de retorno.(Y en realidad también lo mismo que Predicate<string> y Func<string, bool>).Pero como intenté indicar, el "significado" de los dos es diferente.

Esto es algo así como si hiciera dos clases, class Car { string Color; decimal Price; } y class Person { string FullName; decimal BodyMassIndex; }, entonces solo porque ambos tienen un string y un decimal, eso no significa que sean del "mismo" tipo.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top