Creando una función que convierte funciones de un tipo a otro.

Para algunas reflexiones sofisticadas, tengo una función de tipo Func y necesito pasarla a una función que acepte el tipo Func donde T no se conoce hasta el tiempo de ejecución. Por ejemplo:

public bool MyOperation(Func<string,bool> op) {
  return _myValues.Any(op);
}

public static bool InvokeOperationMethod(MethodInfo info, object obj,Func<object,bool> opAsObject)
{
   info.Invoke(obj, opAsObject);
}

El problema es que, como tengo un lambda de un tipo más débil, no puedo pasarlo como un argumento de un tipo más fuerte. Así que traté de hacer un ayudante que cree una función que convierta un lambda de un tipo más débil en un tipo más fuerte. Por ejemplo, podría llamar

var converter = CreateConverter(typeof(string));
Func<object,bool> asObject = o => o.ToString() == "a string"; //Dump example
Func<string,bool> asString = (Func<string,bool>)converter(asObject);
Assert.IsTrue(asInt("a string"));

Por supuesto, en el código real, este tipo de destino no se conoce hasta el tiempo de ejecución, y el predicado real no es una prueba trivial.

Este es mi intento:

/// <summary>
/// Converts a predicate of Func<object,bool> to
/// Func<Type,bool> of the given type.
/// </summary>
/// <param name="destType">Type of the dest.</param>
/// <param name="predicate">The predicate.</param>
/// <returns></returns>
public static TransformPredicate CreateConverter(Type destType)
{
    // This essentially creates the following lambda, but uses destType instead of T
    // private static Func<Func<object, bool>, Func<T, bool>> Transform<T>()
    // { 
    //     return (Func<object,bool> input) => ((T x) => input(x));
    // }
    var input = Expression.Parameter(typeof(Func<object, bool>), "input");

    var x = Expression.Parameter(destType, "x");
    var convert = Expression.Convert(x, typeof(object));
    var callInputOnX = Expression.Invoke(input, convert);
    var body2 = Expression.Lambda(callInputOnX, x);
    var body1 = Expression.Lambda(typeof(TransformPredicate),body2, input);
    return (TransformPredicate) body1.Compile();
}

public delegate object TransformPredicate(Func<object,bool> weak);

Esto realmente funciona bien, excepto que se ejecuta muy lentamente ya que invoca implícitamente a CreateDelegate en cada invocación. Así que traté de llamarme CreateDelegate agregando:

var destFunc = typeof(Func<,>).MakeGenericType(destType, typeof(bool));
var endType = typeof(Func<,>).MakeGenericType(typeof(Func<object, bool>), destFunc);
return (TransformPredicate)compiled.Method.CreateDelegate(endType);

Esto resulta en un error:

System.NotSupportedException: las clases derivadas deben proporcionar e implementar.

¿Alguna idea de cómo puedo llamarme CreateDelegate?

Respuestas a la pregunta(1)

Su respuesta a la pregunta