mercredi 20 septembre 2023

How can I get the MethodInfo of Expression.Lambda

I'm trying to get the MethodInfo of the static Expression.Lambda<TDelegate>(Expression, ParameterExpression[]) method. But I'm getting an AmbiguousMatchException when I try with GetMetod:

MethodInfo lambda = typeof(Expression).GetMethod(nameof(Expression.Lambda), new[] { typeof(Expression), typeof(ParameterExpression[]) });

I have figured out a very convoluted way by getting all public static methods and filtering:

MethodInfo lambda = (
    from m in typeof(Expression).GetMethods(BindingFlags.Public | BindingFlags.Static)
    let p = ((MethodBase)m.ReturnParameter.Member).GetParameters()
    where m.Name == nameof(Expression.Lambda) && m.ReturnType.IsGenericType 
                                              && p.Length == 2 
                                              && p[0].ParameterType == typeof(Expression) 
                                              && p[1].ParameterType == typeof(ParameterExpression[])
    select m
).Single();

It works but seems overly complicated and pretty dangerous (cast to MethodBase plus Single() call).

Is there a simpler solution to get that generic MethodInfo?





Aucun commentaire:

Enregistrer un commentaire