Вопрос: Получить значение int из enum в C #


У меня есть класс, называемый Questions(Множественное число). В этом классе есть перечисление, называемое Question(единственного числа), который выглядит следующим образом.

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

в Questionsкласс, у меня есть get(int foo)функция, которая возвращает Questionsобъект для этого foo, Есть ли простой способ получить целочисленное значение из перечисления, чтобы я мог сделать что-то вроде Questions.Get(Question.Role)?


1346


источник


Ответы:


Просто введите перечисление, например.

int something = (int) Question.Role;

Вышеупомянутое будет работать для подавляющего большинства перечислений, которые вы видите в дикой природе, поскольку основной тип по умолчанию для перечисления int,

Однако, поскольку cecilphillip указывает, что перечисления могут иметь разные базовые типы. Если перечисление объявлено как uint, long, или ulong, он должен быть привязан к типу перечисления; например для

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

вы должны использовать

long something = (long)StarsInMilkyWay.Wolf424B;

1764



Поскольку Enums может быть любым интегральным типом ( byte, int, shortи т. д.), более надежный способ получить базовое интегральное значение перечисления будет состоять в использовании GetTypeCodeметода в сочетании с Convertкласс:

enum Sides {
    Left, Right, Top, Bottom
}
Sides side = Sides.Bottom;

object val = Convert.ChangeType(side, side.GetTypeCode());
Console.WriteLine(val);

Это должно работать независимо от базового интегрального типа.


233



Объявите его как статический класс с общедоступными константами:

public static class Question
{
    public const int Role = 2;
    public const int ProjectFunding = 3;
    public const int TotalEmployee = 4;
    public const int NumberOfServers = 5;
    public const int TopBusinessConcern = 6;
}

И тогда вы можете ссылаться на него как Question.Role, и он всегда оценивает intили как вы его определяете.


160



Question question = Question.Role;
int value = (int) question;

В результате value == 2,


71



В соответствующей заметке, если вы хотите получить intценность от System.Enum, затем eВот:

Enum e = Question.Role;

Вы можете использовать:

int i = Convert.ToInt32(e);
int i = (int)(object)e;
int i = (int)Enum.Parse(e.GetType(), e.ToString());
int i = (int)Enum.ToObject(e.GetType(), e);

Последние два уродливые. Я предпочитаю первый.


53



It's easier than you think - an enum is already an int. It just needs to be reminded:

int y = (int)Question.Role;
Console.WriteLine(y); // prints 2

29



Example:

Public Enum EmpNo
{
    Raj = 1
    Rahul,
    Priyanka
}

And in the code behind to get enum value:

int setempNo = (int)EmpNo.Raj; //This will give setempNo = 1

or

int setempNo = (int)EmpNo.Rahul; //This will give setempNo = 2

Enums will increment by 1, and you can set the start value. Else it will be assigned as 0 initially.


21



I have recently converted away from using enums in my code in favour of instead using classes with protected constructors and predefined static instances (thanks to Roelof - C# Ensure Valid Enum Values - Futureproof Method).

In light of that, below's how I'd now approach this issue (including implicit conversion to/from int).

public class Question
{
    // Attributes
    protected int index;
    protected string name;
    // Go with a dictionary to enforce unique index
    //protected static readonly ICollection<Question> values = new Collection<Question>();
    protected static readonly IDictionary<int,Question> values = new Dictionary<int,Question>();

    // Define the "enum" values
    public static readonly Question Role = new Question(2,"Role");
    public static readonly Question ProjectFunding = new Question(3, "Project Funding");
    public static readonly Question TotalEmployee = new Question(4, "Total Employee");
    public static readonly Question NumberOfServers = new Question(5, "Number of Servers");
    public static readonly Question TopBusinessConcern = new Question(6, "Top Business Concern");

    // Constructors
    protected Question(int index, string name)
    {
        this.index = index;
        this.name = name;
        values.Add(index, this);
    }

    // Easy int conversion
    public static implicit operator int(Question question) =>
        question.index; //nb: if question is null this will return a null pointer exception

    public static implicit operator Question(int index) =>        
        values.TryGetValue(index, out var question) ? question : null;

    // Easy string conversion (also update ToString for the same effect)
    public override string ToString() =>
        this.name;

    public static implicit operator string(Question question) =>
        question?.ToString();

    public static implicit operator Question(string name) =>
        name == null ? null : values.Values.FirstOrDefault(item => name.Equals(item.name, StringComparison.CurrentCultureIgnoreCase));


    // If you specifically want a Get(int x) function (though not required given the implicit converstion)
    public Question Get(int foo) =>
        foo; //(implicit conversion will take care of the conversion for you)
}

The advantage of this approach is you get everything you would have from the enum, but your code's now much more flexible, so should you need to perform different actions based on the value of Question, you can put logic into Question itself (i.e. in the preferred OO fashion) as opposed to putting lots of case statements throughout your code to tackle each scenario.


NB: Answer updated 2018-04-27 to make use of C# 6 features; i.e. declaration expressions and lambda expression body definitions. See revision history for original code. This has the benefit of making the definition a little less verbose; which had been one of the main complaints about this answer's approach.


16



To ensure an enum value exists and then parse it, you can also do the following.

// Fake Day of Week
string strDOWFake = "SuperDay";
// Real Day of Week
string strDOWReal = "Friday";
// Will hold which ever is the real DOW.
DayOfWeek enmDOW;

// See if fake DOW is defined in the DayOfWeek enumeration.
if (Enum.IsDefined(typeof(DayOfWeek), strDOWFake))
{
// This will never be reached since "SuperDay" 
// doesn't exist in the DayOfWeek enumeration.
    enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWFake);
}
// See if real DOW is defined in the DayOfWeek enumeration.
else if (Enum.IsDefined(typeof(DayOfWeek), strDOWReal))
{
    // This will parse the string into it's corresponding DOW enum object.
    enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWReal);
}

// Can now use the DOW enum object.
Console.Write("Today is " + enmDOW.ToString() + ".");

I hope this helps.


11



If you want to get an integer for the enum value that is stored in a variable, wich the type would be Question, to use for example in a method, you can simply do this I wrote in this example:

enum Talen
{
    Engels = 1, Italiaans = 2, Portugees = 3, Nederlands = 4, Duits = 5, Dens = 6
}

Talen Geselecteerd;    

public void Form1()
{
    InitializeComponent()
    Geselecteerd = Talen.Nederlands;
}

// You can use the Enum type as a parameter, so any enumeration from any enumerator can be used as parameter
void VeranderenTitel(Enum e)
{
    this.Text = Convert.ToInt32(e).ToString();
}

This will change the window title to 4 because the variable Geselecteerd is Talen.Nederlands. If I change it to Talen.Portugees and call the method again, the text will change to 3.

I had a hard time finding this simple solution on the internet and I couldn't find it, so I was testing something and found this out. Hope this helps. ;)


11