Obtain RuntimeMethodHandle from interface?

c# c#-3.0 expression-trees methodhandle

Question

I have a piece of dissassembled code which didn't work quite well around some reflection code. I have no idea on how to make it valid as I don't know how to work with MethodHandles etc... I think it should be a pretty simple task for a reflection guru because (as far as I can deduct) the only thing that needs to happen is 'getting a method handle from an interface'? Am I correct?

The following parameter is wrong.. IProductRepositoryItem.Code should be a RuntimeMethodHandle

(MethodInfo) MethodBase.GetMethodFromHandle(IProductRepositoryItem.Code));

Full code:

ParameterExpression parameterExpression = Expression.Parameter(typeof (T), "i");
// ISSUE: method reference

Expression<Func<T, object>> property =
    Expression.Lambda<Func<T, object>>(
        (Expression) Expression.Property(
            (Expression) Expression.Convert((Expression) parameterExpression, typeof (IProductRepositoryItem)),
            (MethodInfo) MethodBase.GetMethodFromHandle(IProductRepositoryItem.Code)), 
                new ParameterExpression[1] {
                     parameterExpression
                });
string key = entityHelper.GetField<T>(property);

Accepted Answer

Assuming your function has no parameters, you should change the entire offending line to this:

typeof(IProductRepositoryItem).GetMethod("Code");

If it does take parameters, use the appropriate overload of GetMethod.

EDIT: If you're trying to access a property, you should use the overload of Expression.Property that takes a PropertyInfo rather than a MethodInfo.

typeof(IProductRepositoryItem).GetProperty("Code");


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why