Y at-il un moyen plus rapide de lancer Fun<TEntity, TId>
à Func<TEntity, object>
Une manière plus rapide de lancer un Func <T, T2> à Func <T, object>?
public static class StaticAccessors<TEntity>
{
public static Func<TEntity, TId> TypedGetPropertyFn<TId>(PropertyInfo pi)
{
var mi = pi.GetGetMethod();
return (Func<TEntity, TId>)Delegate.CreateDelegate(typeof(Func<TEntity, TId>), mi);
}
public static Func<TEntity, object> ValueUnTypedGetPropertyTypeFn(PropertyInfo pi)
{
var mi = typeof(StaticAccessors<TEntity>).GetMethod("TypedGetPropertyFn");
var genericMi = mi.MakeGenericMethod(pi.PropertyType);
var typedGetPropertyFn = (Delegate)genericMi.Invoke(null, new[] { pi });
//slow: lambda includes a reflection call
return x => typedGetPropertyFn.Method.Invoke(x, new object[] { }); //can we replace this?
}
}
est-il un moyen de convertir typedGetPropertyFn
à un Func<TEntity, object>
sans avoir le code de réflexion dans le lambda retourné comme dans l'exemple ci-dessus?
EDIT: solution modifiée ajouté
Ok merci à 280Z28 pour me conduire sur le droit chemin que j'ai inclus dans la solution finale ci-dessous. J'ai laissé le code de réflexion là pour les plateformes qui ne supportent pas les expressions. Pour les plates-formes qui le font, il montre un 26x à 27x (13/0,5 ticks moy) augmentation perf pour obtenir int
et string
propriétés.
public static Func<TEntity, object> ValueUnTypedGetPropertyTypeFn(PropertyInfo pi)
{
var mi = typeof(StaticAccessors<TEntity>).GetMethod("TypedGetPropertyFn");
var genericMi = mi.MakeGenericMethod(pi.PropertyType);
var typedGetPropertyFn = (Delegate)genericMi.Invoke(null, new[] { pi });
#if NO_EXPRESSIONS
return x => typedGetPropertyFn.Method.Invoke(x, new object[] { });
#else
var typedMi = typedGetPropertyFn.Method;
var obj = Expression.Parameter(typeof(object), "oFunc");
var expr = Expression.Lambda<Func<TEntity, object>> (
Expression.Convert(
Expression.Call(
Expression.Convert(obj, typedMi.DeclaringType),
typedMi
),
typeof(object)
),
obj
);
return expr.Compile();
#endif
}
Que faire si ma fonction initiale renvoie un type de valeur tel que Guid? Ensuite, j'obtiens une erreur d'exécution lorsque je tente de lancer vers Func. –