您可以在运行时添加到枚举类型吗 [英] Can you add to an enum type in run-time
问题描述
如果我有一个枚举类型:
If I have an enum type:
public enum Sport
{
Tennis = 0;
Football = 1;
Squash = 2;
Volleyball = 3;
}
我可以在运行时以某种方式添加:
Can I somehow add during run-time:
PingPong = 4
推荐答案
枚举有一个后备存储,如果你不指定,默认为 int.可以直接分配定义值之外的值:
The enum has a backing store, defaulting to int if you don't specify it. It is possible to directly assign values outside of the defined values:
Sport pingPong = (Sport)4;
然后你可以检查一下:
if (value == (Sport)4) {}
这就是为什么你有静态函数 Enum.IsDefined()
用于检查实际值是否在预期值内.请注意,该函数不适用于复合标志值.
That is why you have the static function Enum.IsDefined()
for checking if the actual value falls inside the expected values. Note that the function doesn't work for compound flag values.
bool isValueDefined = Enum.IsDefined(typeof(Sport), value);
在 Hans Passant 的评论之后:您不必使用文字值 4.您可以使用任何返回 int 的内容.例如:
After Hans Passant's comment: You don't have to use the literal value 4. You could use anything which returns an int. For example:
Dictionary<int, string> AdditionalSports = new Dictionary<int, string>();
AdditionalSports.Add(4, "PingPong");
// Usages: if
if (AdditionalSports.ContainsKey(value))
{
// Maybe do something with AdditionalSports[value], i.e. "PingPong"
}
// In a switch:
switch (value)
{
case default:
// Since it won't be found in the enum-defined values
if (AdditionalSports.ContainsKey(value))
{
// Maybe do something with AdditionalSports[value], i.e. "PingPong"
}
}
这篇关于您可以在运行时添加到枚举类型吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!