简体   繁体   English

调用参数类型为Expression的方法 <Func<T, object> &gt;使用反射

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

I need to call below ExpFunction with reflection: 我需要在反射下调用ExpFunction:

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>> . 可能是因为ExpFunction接受Expression<Func<T, object>> And TestClass.Col is a string. 而且TestClass.Col是一个字符串。

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. 有两个问题,您没有将属性强制转换为Object ,而是对根本不是通用的方法调用了MakeGenericMethod

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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