如果隐藏的目的是使用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
这可能显然对那知道 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.