Can I have a base class where each derived class has its own copy of a static property?

前端 未结 4 2008
伪装坚强ぢ
伪装坚强ぢ 2021-01-13 01:52

I have something like the following situation below:

class Base
{
     public static int x;
     public int myMethod()
     {
          x += 5;
          ret         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-13 02:25

    I usually implement subclass specific stuff as an abstract get property

    public class Base
    {
        // You must pick one option below
    
        // if you have a default value in the base class
        public virtual int x { get { return 7; /* magic default value */} }
    
        // if you don't have a default value
        // if you choose this alternative you must also make the Base class abstract
        public abstract int x { get; }
    }
    
    public class DerivedA : Base
    {
        public override int x { get { return 5; } }
    }
    
    public class DerivedB : Base
    {
        public override int x { get { return 10; } }
    }
    

提交回复
热议问题