如何使用反射获取构造函数作为 MethodInfo

发布于 2024-08-03 09:22:19 字数 356 浏览 2 评论 0原文

构造函数如下所示:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

燕归巢 2024-08-10 09:22:20

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.

滥情稳全场 2024-08-10 09:22:20
ConstructorInfo constructor = typeof(NameAndValue).GetConstructor
        (new Type[] { typeof(string), typeof(string) });

您应该在 ConstructorInfo 中拥有所需的元素,但我知道没有办法获取构造函数的 MethodInfo 。

善良,

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

眼睛会笑 2024-08-10 09:22:20

我相信您唯一缺少的是正确的 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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文