문제

Why in C# am I required to specify the access modifier of the method I'm overriding if I'm not changing it? Wouldn't it be simpler and more logical to not specify any access modifier at all in this situations?

(Just to clarify: I write this question not because I think that I'm smarter then language designers, but because I'm sure that they had a good reason that I can't understand yet.)

Edit: I'm not asking about why we can't change access modifier, but rather about why we have to redundantly specify it.

도움이 되었습니까?

해결책 2

To illustrate Jon's point in code, consider the following:

class LevelOne
{
    public virtual void SayHi()
    {
        Console.WriteLine("Hi!");
    }
}
class LevelTwo : LevelOne
{
    override void SayHi()
    {
        Console.WriteLine("Hi!");
    }
}
class LevelThree : LevelTwo
{
    override void SayHi()
    {
        Console.WriteLine("Hi!");
    }
}

Ad infinitum. Now imagine you're at n-depth of derived classes, you have to follow the inheritance hierarchy all the way back to the original base class to find out the access modifier of the method. That's just plain annoying!

다른 팁

While I'm not one of the language designers, I think it's entirely reasonable to force you to specify it:

  • Anyone reading the code immediately knows the access without having to check the original declaration
  • A change to the access of the original declaration is a breaking change this way, making it much more obvious to the overriding code
  • It makes a method which happens to override a higher declaration consistent with non-overriding methods. (It would be odd for a method with no access modifier to be sometimes public and sometimes private, depending on override.)

Basically, redundancy is sometimes a good thing :)

In order to facilitate understanding of the code by another developer who don't write the code. when you read override you know that you make polymorphism

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top