How to override derived constant classes?

THE CODE:

public class A {
    public const int beingSupportedRate = 0;
}

 public partial class B : A {
    public const int beingSupportedRate = 1;

}

I want it to be explicitly like const int due to performance. Placing a virtual in front of a class Avariable beingSupportedRatecauses a compiler error:

The modifier 'virtual' is not valid for this item

+5
source share
5 answers

In fact, I believe that you misunderstood the point of polymorphism in object-oriented programming.

Constants, fields, and variables are just a repository (well, references, but I speak from a conceptual point of view).

Polymorphism is a change in the behavior of something. Overriding a constant could not change the behavior, but it changed its meaning.

, , , AppDomain .

, ? ?

public class A 
{
      public virtual const int Some = 1;
}

public class B : A
{
      public override const int Some = 2;
}

public class C : A
{
     // No override here!
}

int valueOfSomeConstant = C.Some;

! , C.Some 2, C !

:

, const int - . [...]

: - .

, .

+4

new, :

public class A
{
    public const int beingSupportedRate = 0;
}

public class B : A
{
    public new const int beingSupportedRate = 1;
}

, .

Console.WriteLine(A.beingSupportedRate);
Console.WriteLine(B.beingSupportedRate);

:

0
1

, . , :

class Program
{
    static void Main(string[] args)
    {
        A a = new A();
        B b = new B();
        C c = new C();

        a.GetBeingSupportRate();
        b.GetBeingSupportRate();
        c.GetBeingSupportRate();

        Console.Read();
    }

    public class A
    {
        public const int beingSupportedRate = 0;
        public void GetBeingSupportRate()
        {
            Console.WriteLine(beingSupportedRate);
        }
    }

    public class B : A
    {
        public new const int beingSupportedRate = 1;

    }

    public class C : B
    {

    }
}

0 , A. , , .

, , .

+12

( ) . , ... , ... , , , .

, , , .

, , " , const ", - -. , , , , .

+6

, .

, , , , , abstract virtual .

+5

U , :

public class A 
{
    public virtual Int32 beingSupportedRate
    { 
        get { return 0; }
    }
}

public class B : A
{
    public override Int32 beingSupportedRate 
    {
        get { return 1; }
    }
}
+3
source

All Articles