如何用重载和重写方法解释此行为? [英] How to explain this behaviour with Overloaded and Overridden Methods?

查看:57
本文介绍了如何用重载和重写方法解释此行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能这么好,请解释一下为什么这段代码显示 Derived.DoWork(double).我可以对此行为提出一些解释,但是我希望有人为我澄清一下.

Could anyone be so nice and explain me why this code shows Derived.DoWork(double). I can come up with some explanations for this behaviour, however I want someone to clarify this for me.

using System;

public class Base
{
    public virtual void DoWork(int param) {
        Console.WriteLine("Base.DoWork");
    }
}

public class Derived : Base
{
    public override void DoWork(int param) {
        Console.WriteLine("Derived.DoWork(int)");
    }

    public void DoWork(double param) {
        Console.WriteLine("Derived.DoWork(double)");
    }

    public static void Main() {
        int val = 5;
        Derived d = new Derived();
        d.DoWork(val);
    }
}

推荐答案

埃里克·利珀特(Eric lippert)过去总是说越接近越好" .

Eric lippert used to say always "Closer is better".

首先在派生类中声明的方法比在基类中首先声明的方法更近.

A method first declared in a derived class is closer than a method first declared in a base class.

因此从上面的链接中,派生类更近,因此被选择.

So from the above link, derived class is closer hence that is chosen.

为避免脆性基类问题

为完整起见,我将分享项目符号:

For completeness I'll share the bullets:

  • 首先在派生类中声明的方法比在基类中首先声明的方法更近.

  • A method first declared in a derived class is closer than a method first declared in a base class.

嵌套类中的方法比包含类中的方法更近.

A method in a nested class is closer than a method in a containing class.

任何接收类型的方法都比任何扩展方法都更近.

Any method of the receiving type is closer than any extension method.

在嵌套命名空间的类中找到的扩展方法比在外部命名空间的类中找到的扩展方法更近.

An extension method found in a class in a nested namespace is closer than an extension method found in a class in an outer namespace.

在当前命名空间的类中找到的扩展方法比using指令提到的在命名空间的类中找到的扩展方法更近.

An extension method found in a class in the current namespace is closer than an extension method found in a class in a namespace mentioned by a using directive.

在using指令中提到的命名空间中的类中的扩展方法(其中该指令位于嵌套名称空间中)比在using指令中提到的命名空间的类中的扩展方法更近.在外部名称空间中.

An extension method found in a class in a namespace mentioned in a using directive where the directive is in a nested namespace is closer than an extension method found in a class in a namespace mentioned in a using directive where the directive is in an outer namespace.

这篇关于如何用重载和重写方法解释此行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆