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

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

问题描述

如果我有枚举类型:

 公共枚举体育
{
网球= 0;
足球= 1;
壁球= 2;
排球= 3;
}



我可以在运行时莫名其妙地补充:

 乒乓= 4 


解决方案

枚举有一个后备存储,默认为int,如果你不指定。它可以直接分配定义的值以外的值:

 体育乒乓球=(体育)4; 



然后,你可以检查它:

 如果(价值==(体育)4){} 

这就是为什么你有静态函数 Enum.IsDefined() 了解如果实际值超出预期值内检查。需要注意的是功能不适用于复合的标志值工作。

 布尔isValueDefined = Enum.IsDefined(typeof运算(运动),价值); 



编辑:汉斯帕桑特的评论后:您不必使用文字值4,你可以使用任何它返回一个int值。例如:

 词典< INT,串> AdditionalSports =新词典< INT,串>(); 
AdditionalSports.Add(4,乒乓);

//用法:如果
如果(AdditionalSports.ContainsKey(值))
{
//也许做AdditionalSports [值],即乒乓的东西
}

//在开关:$​​ b $ b开关(值)
{
的情况下默认:
//因为它不会在枚举定义的值
中,如果(AdditionalSports.ContainsKey(值))
{
//也许做AdditionalSports [价值]的东西,也就是乒乓
}
}


If I have the enum type:

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

Can I somehow add during run-time:

PingPong = 4

解决方案

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;

Then you can check for it:

if (value == (Sport)4) {}

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);

EDIT: 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天全站免登陆