1

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?

4
  • Have you tried casting it to an object? Commented Sep 14, 2014 at 9:52
  • Where should I cast it? MemberExpression? Commented Sep 14, 2014 at 9:55
  • The Property seems to be the one that needs to be casted. It could be useful if you add the code that calls to UsingReflection to the question. Commented Sep 14, 2014 at 10:00
  • Added above, inside Main. How do I cast it? Commented Sep 14, 2014 at 10:10

2 Answers 2

2

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 });
}
Sign up to request clarification or add additional context in comments.

Comments

1

The ExpFunction is not generic, so you shouldn't .MakeGenericMethod(typeof(T)) it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.