简体   繁体   中英

How to convert enum to int

In C# we can convert an enum to an int by static typecasting as shown below:

int res = (int)myEnum;

Is any other way to do this conversion?

还有很多其他的方法(包括Convert.ToInt32由acrilige提到),但静态浇铸可能是最好的选择(至于可读性和性能而言)

Best would be:

int res = Convert.ToInt32(myEnum);

OR a static cast

int res = (int)myEnum;

Here is an example enum:

public enum Books
{
    cSharp = 4,
    vb = 6,
    java = 9
}

Then the code snippet to use would be:

Books name = Books.cSharp;
int bookcount = Convert.ToInt32(name);

you can do

int enumInt = Convert.ToInt32(yourEnum);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM