开发者

Enum to Int. Int to Enum . Best way to do conversion?

 public Enum Days
 {
    Monday = 1,
    Tuesday = 2,
    Wednesday = 3,
    Thursday = 4,
    Friday = 5,
    Saturday = 6,
    Sunday = 7
 }

Now I wanted to know how do I get the integer value of an enum and convert an integer value into enum

Will

       int dayNo = (int开发者_运维知识库) Days.Monday;

change the value of dayNo to 1;

and

Will

        Days day = (Days) 2;

assign Days.Tuesday to the variable day ??

How about is this the best way to do the parsing??


Yes, and this is very easy to check:

Days d = (Days)3;
Console.WriteLine(d);

This will output

Wednesday

As a best practice, the name of your enum should be Day not Days; the variable d above represents a Day not Days. See the naming guidelines on MSDN.


Yes it will do exactly that except Enum should be enum

public enum Days
 {
    Monday = 1,
    Tuesday = 2,
    Wednesday = 3,
    Thursday = 4,
    Friday = 5,
    Saturday = 6,
    Sunday = 7
 }

To use Enum.Parse you MUST provide a string so if you want to cast from the int you'd have to go via a string which is ugly.

Days x = (Days)Enum.Parse(typeof(Days), "3");
Days y = (Days)Enum.Parse(typeof(Days), 3.ToString());

... both give you wednesday.


In a word, yes.


Your understanding of enums is correct.

You can use Enum.Parse to convert from number/name to enum type if you feel more comfortable with this method, but it gains nothing in readbility or performance.

Strangely, in order to parse numbers, you need to call ToString() on them first, as Enum.Parse has no integer overload.

From the MSDN page:

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.


Yes it will. But did you try it before posting?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜