小编Zak*_*ley的帖子

如果事先无法知道方法签名,如何从MethodInfo创建委托?

我需要一个方法,该方法接受一个MethodInfo表示具有任意签名的非泛型静态方法的实例,并返回绑定到该方法的委托,该委托稍后可以使用Delegate.DynamicInvoke方法调用.我的第一次天真尝试看起来像这样:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        var method = CreateDelegate(typeof (Console).GetMethod("WriteLine", new[] {typeof (string)}));
        method.DynamicInvoke("Hello world");
    }

    static Delegate CreateDelegate(MethodInfo method)
    {
        if (method == null)
        {
            throw new ArgumentNullException("method");
        }

        if (!method.IsStatic)
        {
            throw new ArgumentNullException("method", "The provided method is not static.");
        }

        if (method.ContainsGenericParameters)
        {
            throw new ArgumentException("The provided method contains unassigned generic type parameters.");
        }

        return method.CreateDelegate(typeof(Delegate)); // This does not work: System.ArgumentException: Type must derive from …
Run Code Online (Sandbox Code Playgroud)

.net c# reflection delegates methodinfo

40
推荐指数
1
解决办法
2万
查看次数

标签 统计

.net ×1

c# ×1

delegates ×1

methodinfo ×1

reflection ×1