Change the static variable in the subclass without changing it in the parent class

I want a.ID () to return 0 and b.ID () to return 1, and here is my code:

public class A {
public static int id;
public int ID() {return id;}
}

public class B : A { }

public class Main {
    void Program() { //This executes when I execute the program
        A.id = 0;
        B.id = 1;
    }
}

But this does not work, it also does not work:

public class A {
    public static int id;
    public int ID() {return id;}
}

public class B : A {
    public new static int id; //id is actually 1 but ID() is still 0
}

public class Main {
    void Program() { //This executes when I execute the program
        A.id = 0;
        B.id = 1;
    }
}

How can i fix this?

+4
source share
3 answers

You can create two static variables and one virtual property

    public class A
    {
        private static int _idA;


        public virtual int Id
        {
            get { return _idA; }
            set { _idA = value; }
        }
    }

    public class B : A
    {
        private static int _idB;
        public override int Id
        {
            get { return _idB; }
            set { _idB = value; }
        }
    }

Or one property and use a new keyword to override it

    public class A
    {
        public static  int Id { get; set; }
    }

    public class B : A
    {
        public static new int Id { get; set; }
    }

To check the first solution, you can try the following

static void Main(string[] args)
{
    A test = new B();

    new B().Id = 3;
    new A().Id = 2;
    test.Id = 1;

    Console.WriteLine(test.Id + " " + new B().Id + " " + new A().Id);
    Console.ReadKey();
}
+2
source

You can make the method IDvirtual and override it in the class Bas follows:

public class A
{
    public static int id;
    public virtual int ID() { return id; }
}

public class B : A
{
    public static int id;

    public override int ID()
    {
        return id;
    }
}

, Reflection:

public class A
{
    public static int id;

    public int ID()
    {
        return (int)this.GetType()
            .GetField("id", BindingFlags.Static | BindingFlags.Public)
            .GetValue(null);
    }
}

public class B : A
{
    public static int id;
}

, ID . , ID .

+1

:

  • , .. int
    • 0
    • 1
    • . A id 33554436
    • (- ) , A id 33554437 ( )

ID:

public class Base
{
    public int ID
    {
        get
        {
            return GetType().MetadataToken;
        }
    }
}

, , , , :

33554436
33554437

, :

33554436
33554438

If you are afraid that the constant journey to reflection will be costly, this is an alternative expression:

public class Base
{
    private readonly Lazy<int> _ID;

    protected Base()
    {
        _ID = new Lazy<int>(() => GetType().MetadataToken);
    }

    public int ID
    {
        get
        {
            return _ID.Value;
        }
    }
}
+1
source

Source: https://habr.com/ru/post/1621109/


All Articles