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

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

Priority of overriding parameter types (Interview Question)

问题

我刚刚遇到了一个面试问题。
我预期输出应该是"Derived.Func(int)",但实际输出是"Derived.Func(object)"。

为什么调用了带有"object"参数的函数,而不是带有"int"参数的函数?

  1. public void Main()
  2. {
  3. //控制台输出会是什么?
  4. Derived d = new Derived();
  5. int i = 10;
  6. d.Func(i);
  7. }
  8. public class Derived : Base
  9. {
  10. public override void Func(int x)
  11. {
  12. Console.WriteLine("Derived.Func(int)");
  13. }
  14. public void Func(object o)
  15. {
  16. Console.WriteLine("Derived.Func(object)");
  17. }
  18. }
  19. public class Base
  20. {
  21. public virtual void Func(int x)
  22. {
  23. Console.WriteLine("Base.Func(int)");
  24. }
  25. }
英文:

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??

  1. public void Main()
  2. {
  3. //What will be written in console output?
  4. Derived d = new Derived();
  5. int i = 10;
  6. d.Func(i);
  7. }
  8. public class Derived : Base
  9. {
  10. public override void Func(int x)
  11. {
  12. Console.WriteLine("Derived.Func(int)");
  13. }
  14. public void Func(object o)
  15. {
  16. Console.WriteLine("Derived.Func(object)");
  17. }
  18. }
  19. public class Base
  20. {
  21. public virtual void Func(int x)
  22. {
  23. Console.WriteLine("Base.Func(int)");
  24. }
  25. }

答案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:

确定