We are currently implementing some kind of "extensible class enum" based on strings. Only part of this C # code is below to facilitate understanding of the problem.
If I run the code below, it writes "BaseValue1" and "BaseValue2" to the console.
If I uncomment the RunClassConstructor line and run the code, it additionally writes "DerivedValue1" and "DerivedValue2" to the console.
This is what I want to achieve, but I want to achieve it without the RunClassConstructor line .
I thought DerivedEnum.AllKeys would lead to the creation of "DerivedValue1" and "DerivedValue2", but obviously this is not the case.
Is it possible to achieve what I want without forcing the user of these "enum classes" to write some kind of magic code or do some kind of fictitious initialization?
using System;
using System.Collections.Generic;
namespace ConsoleApplication
{
public class Program
{
static void Main()
{
foreach (var value in DerivedEnum.AllKeys)
{
Console.WriteLine(value);
}
}
}
public class BaseEnum
{
private static readonly IDictionary<string, BaseEnum> _dictionary = new Dictionary<string, BaseEnum>();
public static ICollection<string> AllKeys
{
get
{
return _dictionary.Keys;
}
}
public static readonly BaseEnum BaseValue1 = new BaseEnum("BaseValue1");
public static readonly BaseEnum BaseValue2 = new BaseEnum("BaseValue2");
protected BaseEnum(string value)
{
_dictionary[value] = this;
}
}
public class DerivedEnum : BaseEnum
{
public static readonly DerivedEnum DerivedValue1 = new DerivedEnum("DerivedValue1");
public static readonly DerivedEnum DerivedValue2 = new DerivedEnum("DerivedValue2");
protected DerivedEnum(string value)
: base(value)
{
}
}
}
Madev source
share