如何使用反射访问显式实现的方法? [英] How can I access an explicitly implemented method using reflection?
本文介绍了如何使用反射访问显式实现的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通常,我会像这样访问反射中的方法:
Usually, I access a method in reflection like this:
class Foo
{
public void M () {
var m = this.GetType ().GetMethod ("M");
m.Invoke(this, new object[] {}); // notice the pun
}
}
但是,当M是显式实现时,此操作将失败:
However, this fails when M is an explicit implementation:
class Foo : SomeBase
{
void SomeBase.M () {
var m = this.GetType ().GetMethod ("M");
m.Invoke(this, new object[] {}); // fails as m is null
}
}
如何使用反射访问显式实现的方法?
How do I access an explicitly implemented method using reflection?
推荐答案
这是因为方法的名称不是"M"
,所以将是"YourNamespace.SomeBase.M"
.因此,您将需要指定该名称(以及相应的 BindingFlags
),或者从接口类型中获取方法.
It's because the name of the method is not "M"
, it will be "YourNamespace.SomeBase.M"
. So either you will need to specify that name (along with appropriate BindingFlags
), or get the method from the interface type instead.
因此,给出以下结构:
namespace SampleApp
{
interface IFoo
{
void M();
}
class Foo : IFoo
{
void IFoo.M()
{
Console.WriteLine("M");
}
}
}
...您可以执行以下操作之一:
...you can do either this:
Foo obj = new Foo();
obj.GetType()
.GetMethod("SampleApp.IFoo.M", BindingFlags.Instance | BindingFlags.NonPublic)
.Invoke(obj, null);
...或者这个:
Foo obj = new Foo();
typeof(IFoo)
.GetMethod("M")
.Invoke(obj, null);
这篇关于如何使用反射访问显式实现的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文