我可以通过类型获取 C# 委托的签名吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/429552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 03:02:18  来源:igfitidea点击:

Can I get the signature of a C# delegate by its type?

c#reflectiondelegates

提问by fastcall

Is there a straightforward way using reflection to get at the parameter list for a delegate if you have its type information?

如果您有委托的类型信息,是否有使用反射获取委托的参数列表的直接方法?

For an example, if I declare a delegate type as follows

例如,如果我声明一个委托类型如下

delegate double FooDelegate (string param, bool condition);

and later get the type information for that delegate type as follows

然后获取该委托类型的类型信息,如下所示

Type delegateType = typeof(FooDelegate);

Is it possible to retrieve the return type (double) and parameter list ({string, bool}) from that type info object?

是否可以从该类型信息对象中检索返回类型(double)和参数列表({string, bool})?

采纳答案by Marc Gravell

    MethodInfo method = delegateType.GetMethod("Invoke");
    Console.WriteLine(method.ReturnType.Name + " (ret)");
    foreach (ParameterInfo param in method.GetParameters()) { 
        Console.WriteLine("{0} {1}", param.ParameterType.Name, param.Name);
    }