C# 带接口的类型推断
就在前几天,我发现了一个bug,我花了一段时间才弄明白。 在通过继承接口执行时,似乎执行了错误的重载。看看这段代码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
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)我想在这个博客中你可以找到解释: 当编译器查找实例方法重载时,它 考虑调用的“目标”的编译时类,以及 查看其中声明的方法。如果找不到合适的, 然后查看父类。。。然后是祖父母班等等。 这意味着,如果在不同级别的 在层次结构中,将首先选择“更深层次”的层次,即使它不是 调用的“更好的功能成员”