开发者

Is it possible in .NET 3.5 to specify an enum type?

I have a enumerator which map to a bunch of int

example

enum MyEnum {
Open = 1,
Closed = 2,
Exit = 4

}

I find though that when I want to assign this to an integer, I have to cast it first.

int myEnumNumber = **(int)** MyEnum.Open;

Is it possible to specify the type of an enum so that it is implicit that there is a integer assigned to any value开发者_如何学Go within the enum? That way, I do not need to keep casting it to an int if I want to use it

thanks


No, this is on purpose - enums have an underlying data type, but they are not considered to be identical, because this possibly creates lots of error possibilities that this way are simple to catch.

For example you say so much about having to cast the num all the time - I can not remember when I did do a cast of an enum last time. And I do a LOT of C# programming.


enum MyEnum : int
{
    Open = 1,
    Closed = 2,
    Exit = 4
}

This is also mentioned here.

However, this does not allow you to avoid casting, this allows it to be used with types other than Int32 (which is the default enum type).

In short, yes, you can specify a type but no, you still have to cast it.


There are a few good reasons and probably a lot of bad ones for converting enum values to ints, I'll assume you have a good reason ;).

If you are doing a lot of int casting an extension method might be helpful, here is a quicky extension method:

public static int EnumCast(this Enum theEnum)
{
    return (int)((IConvertible)theEnum);
}

And an example of usage in a test:

[Test]
public void EnumCastTest()
{
    Assert.That(MyEnum.Exit.EnumCast(), Is.EqualTo(4));
}


You can specify a different underlying type using:

enum : byte MyEnum { ... }

But this does not remove the need to cast to byte (if you really want to). Enums in C# allow you to normally just forget about the underlying type unless your applciation requires it.

Do you really need the underlying integer? It is possible to actually store a string representation of an enumeration value in a database and then recreate the enumeration value from the string at a later point, see this question.

MSDN gives a good tutorial on the do's and don't of enums.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜