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

I have something like the following situation below:

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

}

class DerivedA : Base
{
}

class DerivedB : Base
{
}

I am trying to set this up so that each derived class has its own static instance of x if I do something like this:

 DerivedA.x = 5;
 DerivedB.x = 10;

then at startup:

 DerivedA.myMethod(); //The result will be 10
 DerivedB.myMethod(); //The reusult will be 15

Can I do something like this? How can I customize derived classes to achieve this? Thanks guys.

EDIT: , , , . , , . , , . . , - , . . , , -.. !

+4
4

.

:

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

: . .

Edit:

, . ( , virtual) , :

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"; } }
}

. , , protected, .

+5

, , , .

, , , , , :

class Base<TDescendant>
    where TDescendant : Base
{
     public static int x;
     public int myMethod()
     {
          x += 5;
          return x;
     }

}

class DerivedA : Base<DerivedA>
{
}

class DerivedB : Base<DerivedB>
{
}

, , .

, DerivedA DerivedB, , .

+9

. , .

public class Base
{
    private static Dictionatry<Type,int> _values;

    public int MyMethod()
    {
        _values[this.GetType()]+=5;
        return _values[this.GetType()];
    }
}
+1

get

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; } }
}
0

All Articles