How to call non-generic static extension method with parameters using Reflection

I use the following code to execute methods. It works for standard methods string, for example StartsWith, however, I am trying to use several methods for expanding strings, including overriding for Contains, which is all the same for case insensitivity:

var method = "Contains";
var args = new object[] { "@", StringComparison.OrdinalIgnoreCase };

// This works when called
var mi = m.Type.GetMethod(method, args.Select(a => a.GetType()).ToArray());   
if (mi == null) {
    // This does find the method, but causes an error on Expression.Call below
    mi = typeof(Extensions).GetMethods(BindingFlags.Static | BindingFlags.Public).FirstOrDefault(meth => meth.Name == method);
}

var c = args.Select(a => Expression.Constant(a, a.GetType()));

return Expression.Lambda<Func<T, bool>>(Expression.Call(m, mi, c), e);

Received error:

The static method requires a null instance, the non-static method requires a non-empty instance.

How can i solve this?

For reference, here is the extension Contains:

public static bool Contains(this string source, string toCheck, StringComparison comp) {
    return source.IndexOf(toCheck, comp) >= 0;
}

thank


EDIT

Updated at Balazs request, although now I get the following error:

"System.Linq.Expressions.PropertyExpression" "System.String" "Boolean Contains (System.String, System.String, System.StringComparison)"

:

public static Expression<Func<T, bool>> Build(string member, IEnumerable<object> memberArgs, string method, params object[] args) {
    var e = Expression.Parameter(_type, "e");
    var memberInfo = 
        (MemberInfo) _type.GetField(member) ??
        (MemberInfo) _type.GetProperty(member) ??
        (MemberInfo) _type.GetMethod(member, (memberArgs ?? Enumerable.Empty<object>()).Select(p => p.GetType()).ToArray());
    Expression m;

    if (memberInfo.MemberType == MemberTypes.Method) {
        var a = memberArgs.Select(p => Expression.Constant(p));
        m = Expression.Call(e, (MethodInfo) memberInfo, a);
    }
    else {
        m = Expression.MakeMemberAccess(e, memberInfo);
    }

    var mi = m.Type.GetMethod(method, args.Select(a => a.GetType()).ToArray());
    var c = args.Select(a => Expression.Constant(a, a.GetType()));
    MethodCallExpression call;

    if (mi != null) {
        call = Expression.Call(m, mi, c);
    }
    else {
        mi = typeof(Extensions).GetMethods(BindingFlags.Static | BindingFlags.Public).FirstOrDefault(meth => meth.Name == method);
        var newArgsList = c.ToList<object>();
        newArgsList.Insert(0, m);
        c = newArgsList.Select(a => Expression.Constant(a, a.GetType()));
        call = Expression.Call(null, mi, c);
    }

    return Expression.Lambda<Func<T, bool>>(call, e);           
}
+2
1

null ConsantExpression Expression.Call m c.

+3

All Articles