Why can't I access the constant from the object?

public class Foo
{
    public const int type = 1;
}

Why can't I do this? Is there a reason for this or am I trying to access the constant incorrectly?

new Foo().type;

I know what I can do Foo.type, but given my scenario, I cannot do this. For example, if I have two classes that inherit the base class as follows:

public class Base
{
    ...
}

public class Foo : Base
{
    public const int type = 0;
}

public class Bar : Base
{
    public const int type = 1;
}

public static void printType(Base b)
{
     Console.WriteLine(b.type);
}

I would like to get the property of a typeclass dispatched via the printType () function, but I cannot, because I can only access typefrom the class, not the object.

Work around would be

if(b is Foo){
    Console.Write(Foo.type);
}elseif....

but it seems silly and unviable if you have many subclasses Base

<h / ">

Decision

I ended up using readonlyinstead constas follows:

public readonly int type = 0;
+4
2

, . - ​​ . , :

int x = Foo.type;

, const , # , , . ( , .NET Type, Type.)

EDIT: , , , , . , .

public abstract class Base
{
    public abstract int Type { get; }
}

public class Foo : Base
{
    public override int Type { get { return 0; } }
}

public class Bar : Base
{
    public override int Type { get { return 0; } }
}

, :

public class Base
{
    private readonly int type;
    public int Type { get { return type; } }

    protected Base(int type)
    {
        this.type = type;
    }
}

public class Foo : Base
{
    public Foo() : base(0) {}
}

public class Bar : Base
{
    public Bar() : base(1) {}
}
+10

- ( ) , .NET, Object.GetType().

public static void printType(Base b)
{
     Console.WriteLine(b.GetType().Name);
}

, , . Dictionary<Type, T> . .

public class Base
{
    static internal readonly Dictionary<System.Type, int> TypeMap =
       new Dictionary<System.Type, int>();
}

public class Foo : Base
{
    static Foo { TypeMap.Add(typeof(Foo), 0); }
}

public class Bar : Base
{
    static Bar { TypeMap.Add(typeof(Bar), 1); }
}

public static void printType(Base b)
{
     Console.WriteLine(Base.TypeMap[b.GetType()]);
}

, field-per-object, .

+3

All Articles