L
L
lightman2014-08-13 22:02:57
C++ / C#
lightman, 2014-08-13 22:02:57

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

3. The collection must be inherited with the ability to override keys and/or add new ones in descendant classes:
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

4. It is highly desirable that there is an iteration over the values ​​of the constants (that's why it is a collection!):
foreach (var value in myConst)
{
    Console.WriteLine(value);
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2014-08-13
@Nexelen

Maybe mark the required fields as readonly ?

G
gleb_kudr, 2014-08-14
@gleb_kudr

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 question

Ask a Question

731 491 924 answers to any question