gpt4 book ai didi

c# - 在 C# 中初始化静态字段以用于枚举模式

转载 作者:行者123 更新时间:2023-11-30 13:50:05 25 4
gpt4 key购买 nike

我的问题实际上是关于一种解决 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 中是可能的,我觉得我一定在这里遗漏了什么?

最佳答案

这种模式基本上行不通。拥有一个字典也不是一个好主意 - 我怀疑你想让你的 EnumBase 抽象和通用:

public abstract class EnumBase<T> where T : EnumBase<T>

然后可以有一个 protected 静态成员,它可以通过每个派生类有效地“发布”:

public abstract class EnumBase<T> where T : EnumBase<T>
{
protected static T ValueOfImpl(int value)
{
...
}
}

public class Color : EnumBase<Color>
{
// static fields

// Force initialization on any access, not just on field access
static Color() {}

// Each derived class would have this.
public static Color ValueOf(int value)
{
return ValueOfImpl(value);
}
}

然后这会强制您访问 Color 类本身...由于静态初始化程序,此时字段将被初始化。

不幸的是,要完成所有这些工作,还有很多事情要做:(

关于c# - 在 C# 中初始化静态字段以用于枚举模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7561596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com