How to get constructor as MethodInfo using Reflection

送分小仙女□ 提交于 2020-01-02 00:50:10

问题


The constructor looks like this:

public NameAndValue(string name, string value)

I need to get it as a MethodInfo using Reflection. It tried the following, but it does not find the constructor (GetMethod returns null).

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

What am I doing wrong?


回答1:


Type.GetConstructor. Note this returns a ConstructorInfo rather than a MethodInfo, but they both derive from MethodBase so have mostly the same members.




回答2:


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

You should have the elements you need in the ConstructorInfo, I know of no way to get a MethodInfo for a constructor though.

Kindness,

Dan




回答3:


I believe the only thing you were missing was the correct BindingFlags. I don't specify parameter types in this example but you may do so.

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


来源:https://stackoverflow.com/questions/1378020/how-to-get-constructor-as-methodinfo-using-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!