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

构造函数如下所示:

public NameAndValue(string name, string value) 

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

 MethodInfo constructor = typeof(NameAndValue).GetMethod(".ctor", new[] { typeof(string), typeof(string) }); 

我究竟做错了什么?

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

 ConstructorInfo constructor = typeof(NameAndValue).GetConstructor (new Type[] { typeof(string), typeof(string) }); 

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

善良,

我相信你唯一缺少的是正确的BindingFlags。 我没有在此示例中指定参数类型,但您可以这样做。

 var typeName = "System.Object"; // for example var type = Type.GetType(typeName); var constructorMemberInfos = type.GetMember(".ctor", BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); // Note that constructorMemberInfos will be an array of matches