实例上的 Type.InvokeMember

发布于 2024-12-09 05:08:58 字数 486 浏览 4 评论 0原文

如何在实例上调用 InvokeMember?

例如,如果我想使用实例的参数 "argument string" 调用方法 MyMethod()

MyObject myInstance = MyObject.GetObject();

// ?

我已经尝试过:

myInstance.GetType().InvokeMember("MyMethod",
    BindingFlags.InvokeMethod | BindingFlags.Public,
    null,
    null,
    new Object[] { "argument string" })

但它不起作用,抱怨 MyObject 没有 MyMethod,实际上它是一个实例方法,而不是一个类方法,所以我认为它试图将它作为静态方法调用。

有什么帮助吗?

How can I call InvokeMember on an instance?

For example, if I want to call the method MyMethod() with the argument "argument string" of an instance:

MyObject myInstance = MyObject.GetObject();

// ?

I've tried this:

myInstance.GetType().InvokeMember("MyMethod",
    BindingFlags.InvokeMethod | BindingFlags.Public,
    null,
    null,
    new Object[] { "argument string" })

but it does not work, complaining that MyObject doesn't have MyMethod, and indeed it is an instance method, not a class method, so I think it's trying to invoke it as a static method.

Any help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

青芜 2024-12-16 05:08:58

您的第二个 null 应该是调用的目标:

myInstance.GetType().InvokeMember("MyMethod",
    BindingFlags.InvokeMethod | BindingFlags.Public,
    null,
    myInstance,
    new Object[] { "argument string" })

请参阅 有关更多详细信息,请参阅文档

Your second null should be the target of the invocation:

myInstance.GetType().InvokeMember("MyMethod",
    BindingFlags.InvokeMethod | BindingFlags.Public,
    null,
    myInstance,
    new Object[] { "argument string" })

See the documentation for more details.

醉南桥 2024-12-16 05:08:58

怎么样:

MethodInfo method = typeof(MyObject).GetMethod("MyMethod", BindingFlags.Public | BindingFlags.Instance);
method.Invoke(myInstance, new object[] { "argument string" });

How about:

MethodInfo method = typeof(MyObject).GetMethod("MyMethod", BindingFlags.Public | BindingFlags.Instance);
method.Invoke(myInstance, new object[] { "argument string" });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文