英文:
Priority of overriding parameter types (Interview Question)
问题
我刚刚遇到了一个面试问题。
我预期输出应该是"Derived.Func(int)",但实际输出是"Derived.Func(object)"。
为什么调用了带有"object"参数的函数,而不是带有"int"参数的函数?
public void Main()
{
//控制台输出会是什么?
Derived d = new Derived();
int i = 10;
d.Func(i);
}
public class Derived : Base
{
public override void Func(int x)
{
Console.WriteLine("Derived.Func(int)");
}
public void Func(object o)
{
Console.WriteLine("Derived.Func(object)");
}
}
public class Base
{
public virtual void Func(int x)
{
Console.WriteLine("Base.Func(int)");
}
}
英文:
I just got caught on interview question.
I expected the output to be "Derived.Func(int)" but actual output was "Derived.Func(object)"
Why function with object argument was called and not function with int argument??
public void Main()
{
//What will be written in console output?
Derived d = new Derived();
int i = 10;
d.Func(i);
}
public class Derived : Base
{
public override void Func(int x)
{
Console.WriteLine("Derived.Func(int)");
}
public void Func(object o)
{
Console.WriteLine("Derived.Func(object)");
}
}
public class Base
{
public virtual void Func(int x)
{
Console.WriteLine("Base.Func(int)");
}
}
答案1
得分: 3
简而言之,因为规范是这样规定的。如果我理解正确,以下是《12.8.9.2 方法调用》部分的相关内容:
候选方法集被缩小为仅包含来自最派生类型的方法:对于集合中的每个方法C.F
,其中C
是声明方法F
的类型,将从集合中删除在C
的基类型中声明的所有方法。
至于为什么要这样做,是为了防止脆弱的基类问题,正如Eric Lippert所解释的那样。
英文:
In short - because specification says so. If understand correctly here is the relevant part of the 12.8.9.2 Method invocations section:
> The set of candidate methods is reduced to contain only methods from the most derived types: For each method C.F
in the set, where C
is the type in which the method F
is declared, all methods declared in a base type of C
are removed from the set.
For reasons why exactly - to prevent brittle/fragile base class problem as explained by Eric Lippert.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论