Use new keyword if hiding was intended

后端 未结 4 1013
日久生厌
日久生厌 2020-12-13 23:11

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)
{
          


        
4条回答
  •  甜味超标
    2020-12-14 00:03

    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
    

    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.

    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.

提交回复
热议问题