문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top