Answer the question
In order to leave comments, you need to log in
How to implement a collection of constants in C#?
1. Constants will be written in the source code and, therefore, will be known already at the compilation stage.
2. Constants in the collection must be accessible through a dot (for studio intelligence to work):
myConst.A = "a";
myConst.B = "b";
...
Console.WriteLine(myConst.A); // вывод: a
Console.WriteLine(myConst.B); // вывод: b
class A
{
myConst.A = "a";
myConst.B = "b";
}
class B : A
{
myConst.A = "a_new";
myConst.C = "c_new"
}
// мне подойдёт доступ хоть через класс,
// хоть через объект класса, это не важно
B b = new B();
Console.WriteLine(b.myConst.A); // вывод: a_new
Console.WriteLine(b.myConst.B); // вывод: b
Console.WriteLine(b.myConst.C); // вывод: c_new
foreach (var value in myConst)
{
Console.WriteLine(value);
}
Answer the question
In order to leave comments, you need to log in
I think this is how it is possible. + A little reflection. True, the enum will have to include all possible options, including heirs.
using System.Reflection;
public class ConstCollection:Dictionary<MyConst,string>
{
public string A="a";
public string B="b";
public ConstCollection(){
foreach (MyConst c in Enum.GetValues(typeof(MyConst))){
MethodInfo m = this.GetType().GetMethod(c.ToString());
if(m!=null){
string cValue=(string)m.Invoke(this, null);
this.add(c,cValue);
}
}
}
}
public enum MyConst{
A,
B,
C
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question