如果隐藏的目的是使用new关键字 [英] Use new keyword if hiding was intended

查看:143
本文介绍了如果隐藏的目的是使用new关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有正在生成的在VS2008警告:如果隐藏的目的使用new关键字下面的代码片断:

I have the following snippet of code that's generating the "Use new keyword if hiding was intended" warning in VS2008:

public double Foo(double param)
{
   return base.Foo(param);
}



美孚()在基类的功能得到保护,我想通过把它在包装类单独的单元测试的目的,将其暴露在一个单元测试。即包装类将不会被用于其他任何东西。所以,我有一个问题是:这是公认的做法

The Foo() function in the base class is protected and I want to expose it to a unit test by putting it in wrapper class solely for the purpose of unit testing. I.e. the wrapper class will not be used for anything else. So one question I have is: is this accepted practice?

回到警告。 为什么我会有新的压倒一切的功能,在这种情况下?

推荐答案

只是让绝对清楚地表明,你知道你是踩在现有的方法。由于现有的代码是保护,这是不一样大的交易 - 你可以放心地添加停止。它呻吟

The new just makes it absolutely clear that you know you are stomping over an existing method. Since the existing code was protected, it isn't as big a deal - you can safely add the new to stop it moaning.

的差异是当你的方法做一些不同的东西;引用任何变量的导出的类,并调用美孚()会做不同的东西(即使有相同的对象)作为一个引用的的类,并调用美孚()

The difference comes when your method does something different; any variable that references the derived class and calls Foo() would do something different (even with the same object) as one that references the base class and calls Foo():

SomeDerived obj = new SomeDerived();
obj.Foo(); // runs the new code
SomeBase objBase = obj; // still the same object
objBase.Foo(); // runs the old code

这可能显然对那知道<$任何现有代码的影响C $ C> SomeDerived 键,通话美孚() - 也就是说,它现在正在运行一个完全不同的方法。

This could obviously have an impact on any existing code that knows about SomeDerived and calls Foo() - i.e. it is now running a completely different method.

另外请注意,你可以将其标记受保护的内部,并使用 [InternalsVisibleTo] 提供访问您的单元测试(这是最常见的用途 [InternalsVisibleTo] 的;那么你的单元测试可以直接访问它没有派生类

Also, note that you could mark it protected internal, and use [InternalsVisibleTo] to provide access to your unit test (this is the most common use of [InternalsVisibleTo]; then your unit-tests can access it directly without the derived class.

这篇关于如果隐藏的目的是使用new关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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