Creating delegates dynamically with parameter names

后端 未结 3 1422
Happy的楠姐
Happy的楠姐 2020-12-06 02:55

Hi I\'m trying to create a function that dynamically creates a delegate with the same return value and the same parameters as a MethodInfo it receives as parameter and also

3条回答
  •  一个人的身影
    2020-12-06 03:30

    I have just stumbled upon a nice way to solve this issue, it looks like this for delegates to a static method:

    private static Delegate CreateDelegate(MethodInfo method) {
        var paramTypes = method.GetParameters().Select(p => p.ParameterType);
    
        Type delegateType = Expression.GetDelegateType(paramTypes.Append(method.ReturnType).ToArray());
    
        return Delegate.CreateDelegate(delegateType, method, true);
    }
    

    It uses this extension method:

    public static IEnumerable Append(this IEnumerable collection, TSource element) {
        if (collection == null) throw new ArgumentNullException("collection");
    
        foreach (TSource element1 in collection) yield return element1;
        yield return element;
    }
    

提交回复
热议问题