如何使用Reflection将构造函数作为MethodInfo获取

14 .net c# reflection system.reflection

构造函数如下所示:

public NameAndValue(string name, string value)
Run Code Online (Sandbox Code Playgroud)

我需要使用Reflection将其作为MethodInfo.它尝试了以下方法,但它没有找到构造函数(GetMethod返回null).

MethodInfo constructor = typeof(NameAndValue).GetMethod(".ctor", new[] { typeof(string), typeof(string) });
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Phi*_*ney 10

Type.GetConstructor.注意这会返回一个ConstructorInfo而不是MethodInfo,但它们都派生自MethodBase,因此大多数都是相同的成员.


Dan*_*ott 5

ConstructorInfo constructor = typeof(NameAndValue).GetConstructor
        (new Type[] { typeof(string), typeof(string) });
Run Code Online (Sandbox Code Playgroud)

您应该在ConstructorInfo中拥有所需的元素,但我知道无法为构造函数获取MethodInfo.

善良,