【发布时间】:2011-09-26 21:34:07
【问题描述】:
我的问题实际上是关于解决 C# 如何初始化静态字段的方法。我需要这样做,以尝试复制 Java 样式的枚举。以下是显示问题的代码示例:
我的所有枚举都继承自的基类
public class EnumBase
{
private int _val;
private string _description;
protected static Dictionary<int, EnumBase> ValueMap = new Dictionary<int, EnumBase>();
public EnumBase(int v, string desc)
{
_description = desc;
_val = v;
ValueMap.Add(_val, this);
}
public static EnumBase ValueOf(int i)
{
return ValueMap[i];
}
public static IEnumerable<EnumBase> Values { get { return ValueMap.Values; } }
public override string ToString()
{
return string.Format("MyEnum({0})", _val);
}
}
枚举集的样本:
public sealed class Colors : EnumBase
{
public static readonly Colors Red = new Colors(0, "Red");
public static readonly Colors Green = new Colors(1, "Green");
public static readonly Colors Blue = new Colors(2, "Blue");
public static readonly Colors Yellow = new Colors(3, "Yellow");
public Colors(int v, string d) : base(v,d) {}
}
这就是问题所在:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("color value of 1 is " + Colors.ValueOf(2)); //fails here
}
}
上面的代码失败,因为 EnumBase.ValueMap 包含零个项目,因为还没有调用 Color 的构造函数。
看起来这应该不难做到,在Java中是可能的,我觉得我一定是在这里遗漏了什么?
【问题讨论】:
标签: c# initialization enumeration static-members