C#的int枚举转换

C#的int枚举转换

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

问题描述

可能重复:结果
的枚举

如果我有下面的代码:

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

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

会是什么样的转换代码是什么样子?

What would the conversion code look like?

推荐答案

这很好只是你的INT转换为富:

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枚举转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 14:25