C#int到枚举转换[重复]

问题描述 投票:52回答:5

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

转换代码会是什么样的?

c# enums
5个回答
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;这是默认行为。


16
投票

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

foo f = (foo)value;

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

enum foo : int

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

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

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


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

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

2
投票

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

(Foo)1 

它会工作;)

© www.soinside.com 2019 - 2024. All rights reserved.