简体   繁体   中英

Type inference with interfaces

Just the other day I cam across a bug that actually took me a while to figure out. Somehow it seemed that the wrong overload was executed when executing through an inherited interface. Take a look at this code.

class Program
{
    static void Main(string[] args)
    {
        IBar bar = new Bar();                   
        bar.Execute("TEST");
    }
}


public interface IFoo
{
    void Execute(string value);
}

public interface IBar : IFoo
{
    void Execute(object value);
}

public class Foo : IFoo
{
    public void Execute(string value)
    {
        Console.WriteLine("Foo.Execute - string");
    }
}

public class Bar : IBar
{
    public void Execute(string value)
    {
        Console.WriteLine("Bar.Execute - string");
    }

    public void Execute(object value)
    {
        Console.WriteLine("Bar.Execute - object");
    }
}

The output from this program is "Bar-Execute - object" that for me seems a little strange since a more specific overload is available through the inherited IFoo interface. Can anyone explain this behavior?

Best regards

Bernhard Richter

I think in this blog you can find explanation: http://csharpindepth.com/Articles/General/Overloading.aspx

When the compiler goes looking for instance method overloads, it considers the compile-time class of the "target" of the call, and looks at methods declared there. If it can't find anything suitable, it then looks at the parent class... then the grandparent class, etc. This means that if there are two methods at different levels of the hierarchy, the "deeper" one will be chosen first, even if it isn't a "better function member" for the call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM