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

前端 未结 4 2009
伪装坚强ぢ
伪装坚强ぢ 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:38

    You will need to redefine and hide the field and method in all derived types.

    Example:

    class DerivedA : Base
    {
      public new static int x;
      public new int myMethod()
      {
        x += 5;
        return x;
      }
    }
    

    Note: don't do it this way. Fix your design.

    Edit:

    Actually, I have a similar construct. I solve it with an abstract (if you need a default value, use virtual) property which then gets used from the base class:

    public abstract class Base
    {
       public abstract string Name { get; }
    
       public void Refresh()
       {
         //do something with Name
       }
    }
    
    public class DerivedA
    {
      public override string Name { get { return "Overview"; } }
    }
    

    You should be able to adjust that for your use case. You can of course make the property protected if only deriving classes should be able to see it.

提交回复
热议问题