[英]How to get constructor as MethodInfo using Reflection
構造函數如下所示:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.