How can I access an explicitly implemented method using reflection?

后端 未结 2 1336
轮回少年
轮回少年 2021-02-09 13:29

Usually, I access a method in reflection like this:

class Foo
{
    public void M () {
        var m = this.GetType ().GetMethod (\"M\");
        m.Invoke(this,          


        
2条回答
  •  长发绾君心
    2021-02-09 14:24

    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.

    So given the following structure:

    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);            
    

    ...or this:

    Foo obj = new Foo();
    typeof(IFoo)
        .GetMethod("M")
        .Invoke(obj, null);  
    

提交回复
热议问题