使用参数类型Expression <func <t,object =“”>&gt;调用方法使用反射</func <t,>

时间:2014-09-14 09:45:36

标签: c# reflection lambda

我需要在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";
    }    
}

这就是我做的事情

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

但在调用期间它说:

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]]'.

可能是因为ExpFunction接受Expression<Func<T, object>>TestClass.Col是一个字符串。

那我该怎么做呢?

2 个答案:

答案 0 :(得分:2)

有两个问题,你没有将属性转换为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 });
}

答案 1 :(得分:0)

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