Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement a const field which in subClasses must be overwrite .net 4

Tags:

c#

oop

c#-4.0

how to implement a const field which in subClasses must be overwrite, i'm using .net 4, C#

because i have many classes they all have a const field(with different value) called 'pName'.

so i want use a interface or abstract class or somthing as a parent and force these classes to override it.

it's CONST field

like image 787
Scott 混合理论 Avatar asked Dec 12 '25 17:12

Scott 混合理论


1 Answers

You cannot override a const; nor can you declare it as static and override it there. What you can do is re-declare it, but that is not robust - in that which version gets used depends on which you ask for (entirely at compile-time - completely unrelated to polymorphism):

public new const int Foo = 12;

I would suggest you use a virtual or abstract property:

public virtual int Foo { get { return 4; } } // subclasses *can* override
public abstract int Foo { get; } // subclasses *must* override

and override:

public override int Foo { get { return 12; } }
like image 102
Marc Gravell Avatar answered Dec 14 '25 20:12

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!