Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 带接口的类型推断_C#_Inheritance_Interface_Clr - Fatal编程技术网

C# 带接口的类型推断

C# 带接口的类型推断,c#,inheritance,interface,clr,C#,Inheritance,Interface,Clr,就在前几天,我发现了一个bug,我花了一段时间才弄明白。 在通过继承接口执行时,似乎执行了错误的重载。看看这段代码 class Program { static void Main(string[] args) { IBar bar = new Bar(); bar.Execute("TEST"); } } public interface IFoo { void Execute(strin

就在前几天,我发现了一个bug,我花了一段时间才弄明白。 在通过继承接口执行时,似乎执行了错误的重载。看看这段代码

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");
    }
}
这个程序的输出是“Bar Execute-object”,这对我来说似乎有点奇怪,因为通过继承的IFoo接口可以使用更具体的重载。有人能解释这种行为吗

致意


伯恩哈德·里希特(Bernhard Richter)

我想在这个博客中你可以找到解释:

当编译器查找实例方法重载时,它 考虑调用的“目标”的编译时类,以及 查看其中声明的方法。如果找不到合适的, 然后查看父类。。。然后是祖父母班等等。 这意味着,如果在不同级别的 在层次结构中,将首先选择“更深层次”的层次,即使它不是 调用的“更好的功能成员”