2

I've just read that when you define a method in a derived class that has the same name as a method described in a base class, you should get the error: "please add the 'override' or 'new' keyword". But despite me trying to cause it to do so by the code below, everything seems to be OK.

I'd like to know why? I use Visual Studio 2010.

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

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

static void Main(string[] args)
{
  Base myBase = new Base();
  Child myChild = new Child();
  myBase.Method();
  myChild.Method();
}

The output I'm getting is as follows.

Base class

Child class

4

3 回答 3

1

They're simply two different methods that happen to have the same name. Which method is bound at compile time depends on the type the compiler sees in any given context.

Note that if this were a compile-time or run-time errors, then library developers could break consuming code simply by adding a new method to a shared base class.

于 2012-09-15T21:02:27.827 回答
1

You don't get an error, you get a compile time warning.

Here is the MSDN documentation that explains it all.

于 2012-09-15T21:02:34.730 回答
1

It isn't an error, it's a warning.

See CS0108: http://msdn.microsoft.com/en-us/library/3s8070fc.aspx

If you want to treat it as an error, you can go to your project's properties, build tab, treat warnings as errors, and check specific warning while putting 108 into the box.

于 2012-09-15T21:08:32.477 回答