Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

c# - 从C#中的枚举获取int值(Get int value from enum in C#)

I have a class called Questions (plural).

(我有一堂课,叫做Questions (复数)。)

In this class there is an enum called Question (singular) which looks like this.

(在此类中,有一个名为Question (单数)的枚举,它看起来像这样。)

public enum Question
{
    Role = 2,
    ProjectFunding = 3,
    TotalEmployee = 4,
    NumberOfServers = 5,
    TopBusinessConcern = 6
}

In the Questions class, I have a get(int foo) function that returns a Questions object for that foo .

(在Questions类中,我有一个get(int foo)函数,该函数返回该fooQuestions对象。)

Is there an easy way to get the integer value from the enum so I can do something like Questions.Get(Question.Role) ?

(有没有一种简单的方法可以从枚举中获取整数值,因此我可以执行Questions.Get(Question.Role) ?)

  ask by jim translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just cast the enum, eg

(只是枚举枚举,例如)

int something = (int) Question.Role;

The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is int .

(上面的方法适用于您在野外看到的绝大多数枚举,因为枚举的默认基础类型是int 。)

However, as cecilphillip points out, enums can have different underlying types.

(但是,正如cecilphillip指出的那样,枚举可以具有不同的基础类型。)

If an enum is declared as a uint , long , or ulong , it should be cast to the type of the enum;

(如果将枚举声明为uintlongulong ,则应将其强制转换为枚举类型;)

eg for

(例如)

enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};

you should use

(你应该使用)

long something = (long)StarsInMilkyWay.Wolf424B;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...