Overriding constants in derived classes in C#

后端 未结 6 1374
说谎
说谎 2020-12-09 14:50

In C# can a constant be overridden in a derived class? I have a group of classes that are all the same bar some constant values, so I\'d like to create a base class that def

6条回答
  •  伪装坚强ぢ
    2020-12-09 15:07

    Edit: This can have unexpected behaviour, see Shai Petel's remark below.

    You can hide the inherited constant in a derived class by declaring the new constant new. I'm not sure this is a good practice, though.

    class A
    {
        protected const int MyConst = 1;
    }
    
    class B : A
    {
        new private const int MyConst = 2;
    }
    

提交回复
热议问题