采用新的方法隐藏用例 [英] Usecases for method hiding using new

查看:84
本文介绍了采用新的方法隐藏用例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是或多或少的这个帖子,但我不能编辑它,我开始这个。随意搬过来的东西,并关闭这一个。

This is more or less an exact duplicate of this post, but as I cannot edit it, I started this. Feel free to move something over and close this one.

使用方法与新的隐藏似乎是一个危险的特性,并考虑在其他线程的讨论,似乎这不是只有我谁发现有这种有效的用例的问题。任何方法接受基本不会利用所产生的方法。

Using method hiding with new seems like a dangerous feature, and given the discussion in the other thread, it seems it's not only I who have problems finding a valid use case for this. Any methods accepting Base won't use Derived's Method.

public class Base
{
    public void Method()
    {
        Console.WriteLine("Base");
    }
}

public class Derived : Base
{
    public new void Method()
    {
        Console.WriteLine("Derived");
    }
}

var derived = new Derived();
derived.Method(); // "Derived"
((Base)derived).Method(); // "Base"



那么,什么是一些有效的用例新是很难与其他解决特点?

So what are some valid use cases for new that is difficult to solve with other features?

推荐答案

这样做是为了避免的 脆基类的尽可能问题。

The idea is to avoid the brittle base class problem as far as possible.

假设你提供一个图书馆,我从你的类之一派生。创建我自己的方法,美孚(),并适当地调用它。精细。

Suppose you provide a library, and I derive from one of your classes. I create my own method, Foo(), and call it appropriately. Fine.

现在你介绍你的库的第二个版本,并新增了美孚()法(用相同的签名)基类。现在,你的代码将调用美孚(),它有一个特别的意义...这可能是一个的完全不同的的意思是我的美孚()方法。 (如果您添加修改和行为)的默认行为是对事物的行为,他们应该:代码,只知道基类将调用你的方法 - 这是好的,因为这是他们的意思。它采用具有我的派生类的编译时类型将使用表达式代码的我的的方法 - 这很好,因为那是什么的他们的应该是说为好。 (基本上,它只能是我的代码,因为只有我的代码知道我的课。)

Now you introduce a second version of your library, and you add the Foo() method (with the same signature) to the base class. Now your code will call Foo(), which has one particular meaning... and that may be a completely different meaning to my Foo() method. The default behaviour (and the behaviour if you add the new modifier) is for things to behave as they should: code which only knows about the base class will call your method - which is fine, as that's what they mean. Code which uses an expression which has a compile-time type of my derived class will use my method - and that's fine, as that's what they should mean as well. (Basically it can only be my code, because only my code knows about my class.)

应该的一般的避免 - 它可以导致以微妙的错误在哪里改变变量的编译时类型默默地改变行为......但它是否出现那种情况。基本上,加入方法为基类不应该打破派生类,尽可能

It should usually be avoided - it can lead to subtle bugs where changing the compile-time type of the variable silently changes the behaviour... but it's present for that sort of situation. Basically, adding a method to a base class shouldn't break derived classes, as far as possible.

这篇关于采用新的方法隐藏用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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