C#int到枚举转换 [英] C# int to enum conversion

查看:157
本文介绍了C#int到枚举转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在C#中将int int枚举到

Possible Duplicate:
Cast int to enum in C#

如果我有以下代码:

enum foo : int
{
    option1 = 1,
    option2,
    ...
}

private foo convertIntToFoo(int value)
{
    // Convert int to respective Foo value or throw exception
}

转换代码是什么样的?

推荐答案

只要将您的int转换为Foo就可以了:

It's fine just to cast your int to Foo:

int i = 1;
Foo f = (Foo)i;

如果您尝试转换未定义的值,它仍然可以工作。可能来自这个的唯一的伤害是你以后如何使用这个值。

If you try to cast a value that's not defined it will still work. The only harm that may come from this is in how you use the value later on.

如果你真的想确保你的值在枚举中定义,你可以使用Enum.IsDefined:

If you really want to make sure your value is defined in the enum, you can use Enum.IsDefined:

int i = 1;
if (Enum.IsDefined(typeof(Foo), i))
{
    Foo f = (Foo)i;
}
else
{
   // Throw exception, etc.
}

但是,使用IsDefined的成本不仅仅是投射。你使用的取决于你的实施。您可能会考虑限制用户输入,或使用枚举时处理默认情况。

However, using IsDefined costs more than just casting. Which you use depends on your implemenation. You might consider restricting user input, or handling a default case when you use the enum.

另请注意,您不必指定您的枚举从int继承;这是默认行为。

Also note that you don't have to specify that your enum inherits from int; this is the default behavior.

这篇关于C#int到枚举转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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