C#int枚举转换

时间:2009-02-02 11:30:14

标签: c# enums

  

可能重复:
  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
}

转化代码会是什么样的?

5 个答案:

答案 0 :(得分:115)

将你的int转换为Foo是好的:

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

如果您尝试投射未定义的值,它仍然有效。可能由此产生的唯一伤害是您以后如何使用该值。

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

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

然而,使用IsDefined的成本不仅仅是投射。您使用哪个取决于您的实施。您可以考虑在使用枚举时限制用户输入或处理默认情况。

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

答案 1 :(得分:16)

我很确定你可以在这里做明确的演员。

foo f = (foo)value;

只要你说enum从int继承(?),你就拥有它。

enum foo : int

编辑是的,事实证明,默认情况下,枚举基础类型为int。但是,您可以使用除char之外的任何整数类型。

您还可以从不在枚举中的值进行转换,从而产生无效的枚举。我怀疑这只是改变引用的类型而不是实际改变内存中的值。

enum (C# Reference)
Enumeration Types (C# Programming Guide)

答案 2 :(得分:5)

施法应该足够了。如果你正在使用C#3.0,你可以使用一个方便的扩展方法来解析枚举值:

public static TEnum ToEnum<TInput, TEnum>(this TInput value)
{
    Type type = typeof(TEnum);

    if (value == default(TInput))
    {
        throw new ArgumentException("Value is null or empty.", "value");
    }

    if (!type.IsEnum)
    {
        throw new ArgumentException("Enum expected.", "TEnum");
    }

    return (TEnum)Enum.Parse(type, value.ToString(), true);
}

答案 3 :(得分:4)

if (Enum.IsDefined(typeof(foo), value))
{
   return (Foo)Enum.Parse(typeof(foo), value);
}

希望这有帮助

修改 这个答案得到了投票,我的例子中的值是一个字符串,其中问题是int。我的applogies;以下应该更清楚: - )

Type fooType = typeof(foo);

if (Enum.IsDefined(fooType , value.ToString()))
{
   return (Foo)Enum.Parse(fooType , value.ToString());
}

答案 4 :(得分:2)

您不需要继承。你可以这样做:

(Foo)1 

它会起作用;)