美文网首页通往成功之路
C#基础-方法的重写(new)和覆盖(override)

C#基础-方法的重写(new)和覆盖(override)

作者: 此十八 | 来源:发表于2018-04-26 15:31 被阅读0次

    最近又再看基础知识了。

    看到方法的重写(new)和覆盖(override)的时候有点不太懂。

    于是百度之。

    那答案啊。。。。。

    要么就是把覆盖(override)和重载(overload)混淆了。

    要么就是把重写(new)和覆盖(override)说反了。

    最后不得已谷歌之。

    在stackoverflow里看到一个比较好的答案:

    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    virtual: indicates that a function may be overriden by an inheritor

    override: overrides the functionality of a virtual function in a base class, providing different functionality.

    new:hidesthe original function (which doesn't have to be virtual), providing different functionality. This should only be used where it is absolutely necessary.

    When you hide a method, you can still access the original method by up casting to the base class. This is useful in some scenarios, but dangerous.

    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    翻译过来就是(翻译不对的地方请指正,tks):

    override(覆盖):

    virtual:表示这个方法也许会被继承者(子方法)覆盖(override)

    override:覆盖基类中的虚方法,提供不同的实现方法

    new(重写) :

    隐藏原始方法(不必是虚方法),提供不同的实现方法。这个(重写)应该仅用于必须要用的地方(也就是一般地方不推荐使用)。

    当你隐藏一个方法,你仍然可以访问原始方法通过指向基类。这在一些场景中很有用,但是比较危险。

    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    所以呢,

    override一般是拓展原始虚方法,原始方法必须要加上virtual修饰符。

    new 一般是用来拓展原始非虚方法,但是不推荐使用。

    个人理解,如有不正,不吝赐教!

    相关文章

      网友评论

        本文标题:C#基础-方法的重写(new)和覆盖(override)

        本文链接:https://www.haomeiwen.com/subject/yyfmlftx.html