如何使用反射获取构造函数作为 MethodInfo
构造函数如下所示:
public NameAndValue(string name, string value)
我需要使用反射将其作为 MethodInfo 获取。它尝试了以下操作,但没有找到构造函数(GetMethod
返回 null
)。
MethodInfo constructor = typeof(NameAndValue).GetMethod(".ctor", new[] { typeof(string), typeof(string) });
我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Type.GetConstructor。请注意,这会返回 ConstructorInfo 而不是 MethodInfo,但它们都派生自 MethodBase,因此具有大部分相同的成员。
Type.GetConstructor. Note this returns a ConstructorInfo rather than a MethodInfo, but they both derive from MethodBase so have mostly the same members.
您应该在 ConstructorInfo 中拥有所需的元素,但我知道没有办法获取构造函数的 MethodInfo 。
善良,
丹
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
我相信您唯一缺少的是正确的 BindingFlags。我在此示例中没有指定参数类型,但您可以这样做。
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.