可以在运行时添加枚举类型 [英] Can you add to an enum type in run-time

查看:159
本文介绍了可以在运行时添加枚举类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有枚举类型:

Public enum Sport
{
    Tennis = 0;
    Football = 1;
    Squash = 2;
    Volleyball = 3;
}

我可以在运行时添加:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆