【发布时间】:2016-01-11 16:29:21
【问题描述】:
我们目前正在实现某种基于字符串的“可扩展枚举类”。下面只展示这段C#代码的一部分,让问题更容易理解。
如果我运行下面的代码,它会将“BaseValue1”和“BaseValue2”写入控制台。
如果我取消注释 RunClassConstructor 行并运行代码,它还会将“DerivedValue1”和“DerivedValue2”写入控制台。
这就是我想要实现的目标,但我希望在 RunClassConstructor 行的情况下实现它。
我以为DerivedEnum.AllKeys会触发“DerivedValue1”和“DerivedValue2”的创建,但显然不是这样的。
是否有可能实现我想要的,而不强迫这些“枚举类”的用户编写一些魔术代码或进行某种虚拟初始化?
using System;
using System.Collections.Generic;
namespace ConsoleApplication
{
public class Program
{
static void Main()
{
//System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(DerivedEnum).TypeHandle);
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)
{
}
}
}
【问题讨论】:
-
When do static variables get initialized in C#?, Is there a way to force static fields to be initialized in C#?,因此您需要实例化
DerivedEnum或访问其静态成员之一。
标签: c# enums static initialization