vendredi 28 février 2020

Make delegate for method at runtime

I found this interesting article Reflection Performance - Create Delegate (Properties C#)

the described approach works great for properties. So I tried to to make it work for Methods, too, but without success.

Methods looks like:

public class Person
{ public string Name { get; set; } }
public class Process
{
    public Person GetPersonByName(string PersonName)
    {
         // lookup person
         return person;
    }
}

my current Approach looks like:

public static Func<object, string, object> BuildMethodAccessor(MethodInfo method)
    {
        var obj = Expression.Parameter(typeof(object), "o");
        var strParam = Expression.Parameter(typeof(string), "strParam");
        //var param = method.GetParameters().Select(p => Expression.Parameter(p.ParameterType, p.Name)).FirstOrDefault();
        var param = Expression.Convert(strParam, method.GetParameters().First().ParameterType);

        Expression<Func<object, string, object>> expr =
            Expression.Lambda<Func<object, string, object>>(
                Expression.Convert(Expression.Call(Expression.Convert(obj, method.DeclaringType), method, param),
                    typeof(object)),
                obj);

        return expr.Compile();

    }

this code generates messages, that for the lambda-declaration a wrong number of Parameters was used. thx a lot for your help!





Aucun commentaire:

Enregistrer un commentaire