How to create a delegate from a MethodInfo when method signature cannot be known beforehand?

后端 未结 2 2134
囚心锁ツ
囚心锁ツ 2020-12-07 16:31

I need a method that takes a MethodInfo instance representing a non-generic static method with arbitrary signature and returns a delegate bound to that method t

2条回答
  •  旧巷少年郎
    2020-12-07 17:13

    You may want to try System.LinQ.Expressions

    ...
    using System.Linq.Expressions;
    ...
    
    static Delegate CreateMethod(MethodInfo method)
    {
        if (method == null)
        {
            throw new ArgumentNullException("method");
        }
    
        if (!method.IsStatic)
        {
            throw new ArgumentException("The provided method must be static.", "method");
        }
    
        if (method.IsGenericMethod)
        {
            throw new ArgumentException("The provided method must not be generic.", "method");
        }
    
        var parameters = method.GetParameters()
                               .Select(p => Expression.Parameter(p.ParameterType, p.Name))
                               .ToArray();
        var call = Expression.Call(null, method, parameters);
        return Expression.Lambda(call, parameters).Compile();
    }
    

    and use it later as following

    var method = CreateMethod(typeof (Console).GetMethod("WriteLine", new[] {typeof (string)}));
    method.DynamicInvoke("Test Test");
    

提交回复
热议问题