简体   繁体   中英

Call a method with parameter type Expression<Func<T, object>> using reflection

I need to call below ExpFunction with reflection:

class Program
{
    static void Main(string[] args)
    {    
        ExpClass<TestClass> obj = new ExpClass<TestClass>();   

        //without reflection
        obj.ExpFunction(f => f.Col); 

        //with reflection
        UsingReflection<TestClass>(obj, typeof(TestClass).GetProperty("Col"));   
    }
}    
public class TestClass
{
    public string Col { get; set; }
}   
public class ExpClass<T>
{

    public string ExpFunction(Expression<Func<T, object>> propertyMap)
    {
        return "success";
    }    
}

Here is what I did

    static void UsingReflection<T>(ExpClass<T> obj, PropertyInfo Property)
    {
        ParameterExpression parameter = Expression.Parameter(typeof(T), "i");
        MemberExpression property = Expression.Property(parameter, Property);
        var propertyExpression = Expression.Lambda(property, parameter);

        var method = typeof(ExpClass<T>).GetMethod("ExpFunction").MakeGenericMethod(typeof(T));

        method.Invoke(obj, new object[] { propertyExpression });
    }

But During invoke it says:

Object of type 'System.Linq.Expressions.Expression`1[System.Func`2[ExpressionTest.TestClass,System.String]]' 
cannot be converted to type 'System.Linq.Expressions.Expression`1[System.Func`2[ExpressionTest.TestClass,System.Object]]'.

It is probably because ExpFunction accepts Expression<Func<T, object>> . And TestClass.Col is a string.

So how can I do it?

There are two problems, you're not casting the property to Object and you call MakeGenericMethod on a method which is not generic at all.

static void UsingReflection<T>(ExpClass<T> obj, PropertyInfo Property)
{
    ParameterExpression parameter = Expression.Parameter(typeof(T), "i");

    MemberExpression property = Expression.Property(parameter, Property);
    var castExpression = Expression.TypeAs(property, typeof(object));
    var propertyExpression = Expression.Lambda(castExpression, parameter);

    var method = typeof(ExpClass<T>).GetMethod("ExpFunction");

    method.Invoke(obj, new object[] { propertyExpression });
}

ExpFunction不是通用的,因此您不应该.MakeGenericMethod(typeof(T))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM