覆盖参数类型的优先级(面试问题)

huangapple go评论96阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年8月8日 21:56:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76860252.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定