Overriding constants in derived classes in C#

后端 未结 6 1390
说谎
说谎 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:04

    Constants marked with const cannot be overridden as they are substituted by the compiler at compile time.

    But regular static fields assigned to constant values can. I've had such a case just now:

    class Columns
    {
        public static int MaxFactCell = 7;
    }
    
    class Columns2 : Columns
    {
        static Columns2()
        {
            MaxFactCell = 13;
        }
    }
    

    If I just redefined the MaxFactCell field in the derived class instead, polymorphism wouldn't work: code using Columns2 as Columns would not see the overriding value.

    If you need to restrict write (but not read) access to the field, using readonly would prohibit redefining it in Columns2. Make it a property instead, that's slightly more code:

    class Columns
    {
        static Columns()
        {
            MaxFactCell = 7;
        }            
        public static int MaxFactCell { get; protected set; }
    }
    
    class Columns2 : Columns
    {
        static Columns2()
        {
            MaxFactCell = 13;
        }
    }
    

提交回复
热议问题