Comment obtenir constructeur comme MethodInfo utilisant la réflexion
-
21-09-2019 - |
Question
Le constructeur présente comme suit:
public NameAndValue(string name, string value)
Je dois l'obtenir comme un MethodInfo utilisant la réflexion. Il a essayé ce qui suit, mais il ne trouve pas le constructeur (retourne GetMethod
null
).
MethodInfo constructor = typeof(NameAndValue).GetMethod(".ctor", new[] { typeof(string), typeof(string) });
Qu'est-ce que je fais mal?
La solution
Type.GetConstructor . Notez que ce retourne un ConstructorInfo plutôt que d'un MethodInfo, mais ils tirent à la fois de MethodBase ont donc essentiellement les mêmes membres.
Autres conseils
ConstructorInfo constructor = typeof(NameAndValue).GetConstructor
(new Type[] { typeof(string), typeof(string) });
Vous devriez avoir les éléments dont vous avez besoin dans le ConstructorInfo, je ne connais aucun moyen d'obtenir un MethodInfo pour un constructeur bien.
Gentillesse,
Dan
Je crois que la seule chose que vous manquait plus que les BindingFlags corrects. Je ne précise pas les types de paramètres dans cet exemple mais vous pouvez le faire.
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