Get int value from enum in C#

Mam klasę o nazwie Questions (liczba mnoga). W tej klasie istnieje enum o nazwie Question (liczba pojedyncza), które wygląda tak.

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

W klasie Questions mam funkcję get(int foo), która zwraca obiekt Questions dla tego foo. Czy istnieje łatwy sposób na uzyskanie wartości całkowitej z enum, abym mógł zrobić coś takiego jak Questions.Get(Question.Role)?

Author: Sae1962, 2009-06-03

25 answers

Wystarczy rzucić enum, np.

int something = (int) Question.Role;

Powyższe rozwiązanie będzie działać dla zdecydowanej większości enum, ponieważ domyślnym typem bazowym dla enum jest int.

Jednak, jak wskazuje cecilphillip, liczby mogą mieć różne typy bazowe. Jeśli enum jest zadeklarowane jako uint, long, lub ulong, należy go oddać do rodzaju enum; np. dla

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

Powinieneś użyć

long something = (long)StarsInMilkyWay.Wolf424B;
 1849
Author: Tetraneutron,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-27 15:20:50

Ponieważ Enemy mogą być dowolnymi całkami (byte, int, short, itd.), bardziej solidnym sposobem uzyskania podstawowej wartości Całkowej enum byłoby użycie metody GetTypeCode w połączeniu z klasą Convert:

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

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

Powinno to działać niezależnie od podstawowego typu całki.

 242
Author: cecilphillip,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-27 15:05:52

Zadeklaruj ją jako klasę statyczną posiadającą stałe publiczne:

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;
}

I wtedy możesz odwołać się do niego jako Question.Role, i zawsze ocenia się na int lub jak to zdefiniujesz.

 161
Author: PablosBicicleta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-27 16:43:28
Question question = Question.Role;
int value = (int) question;

Spowoduje value == 2.

 72
Author: jerryjvl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-03 06:48:16

W powiązanej notatce, jeśli chcesz uzyskać wartość int z System.Enum, to podaj e tutaj:

Enum e = Question.Role;

Możesz użyć:

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);
Dwie ostatnie są brzydkie. Wolę pierwszą.
 55
Author: nawfal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-13 00:12:45

To łatwiejsze niż myślisz-enum jest już int. Trzeba tylko przypomnieć:

int y = (int)Question.Role;
Console.WriteLine(y); // prints 2
 32
Author: Michael Petrotta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-07 13:52:42

Przykład:

Public Enum EmpNo
{
    Raj = 1
    Rahul,
    Priyanka
}

I w kodzie z tyłu, aby uzyskać wartość enum:

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

Lub

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

Liczby będą wzrastać o 1 i możesz ustawić wartość początkową. W przeciwnym razie zostanie początkowo przypisany jako 0.

 23
Author: Peter Mortensen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-07 20:03:45

Niedawno zrezygnowałem z używania enum w kodzie na rzecz używania klas z chronionymi konstruktorami i predefiniowanymi statycznymi instancjami (dzięki Roelof - C# Enuce Valid Enum Values - Futureproof Method).

W świetle tego, poniżej przedstawiam, jak teraz podchodzę do tego problemu(w tym do niejawnej konwersji do / z 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)
}
Zaletą tego podejścia jest to, że otrzymujesz wszystko, co masz z enum, ale twój kod jest teraz znacznie bardziej elastyczny, jeśli więc będziesz musiał wykonywać różne działania w oparciu o wartość Question, możesz umieścić logikę w samym Question (tj. w preferowanym trybie OO), zamiast umieszczać wiele instrukcji case w całym kodzie, aby rozwiązać każdy scenariusz.

NB: odpowiedź zaktualizowana 2018-04-27, aby korzystać z funkcji C # 6; tj. wyrażeń deklaracji i definicji ciała wyrażeń lambda. Zobacz historię zmian dla oryginalnego kodu. Ma to tę zaletę, że definicja jest trochę mniej gadatliwy; co było jednym z głównych skarg na podejście tej odpowiedzi.

 18
Author: JohnLBevan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-27 08:55:31

Aby upewnić się, że wartość enum istnieje, a następnie ją przeanalizować, możesz również wykonać następujące czynności.

// 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() + ".");
Mam nadzieję, że to pomoże.
 13
Author: Nathon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-23 20:03:17

Jeśli chcesz uzyskać liczbę całkowitą dla wartości enum, która jest przechowywana w zmiennej, której typem będzie Question, Aby użyć na przykład w metodzie, możesz po prostu zrobić to, co napisałem w tym przykładzie:

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();
}

Spowoduje to zmianę tytułu okna na 4, ponieważ zmienna Geselecteerd to Talen.Nederlands. Jeśli zmienię ją na Talen.Portugees i ponownie wywołam metodę, tekst zmieni się na 3.

Trudno mi było znaleźć to proste rozwiązanie w Internecie i nie mogłem go znaleźć, więc testowałem coś i odkryłem to. Mam nadzieję, że to pomoże. ;)

 13
Author: Mathijs Van Der Slagt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-27 16:02:47

Jeszcze jeden sposób:

Console.WriteLine("Name: {0}, Value: {0:D}", Question.Role);

Spowoduje:

Name: Role, Value: 2
 11
Author: plavozont,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-19 05:42:30

Może przeoczyłem, ale czy ktoś próbował prostej, ogólnej metody rozszerzenia. To mi pasuje. W ten sposób można uniknąć typowania w interfejsie API, ale ostatecznie skutkuje to operacją zmiany typu. Jest to dobry przypadek do programowania Roselyn mieć kompilator zrobić metodę GetValue dla Ciebie.

    public static void Main()
    {
        int test = MyCSharpWrapperMethod(TestEnum.Test1);

        Debug.Assert(test == 1);
    }

    public static int MyCSharpWrapperMethod(TestEnum customFlag)
    {
        return MyCPlusPlusMethod(customFlag.GetValue<int>());
    }

    public static int MyCPlusPlusMethod(int customFlag)
    {
        //Pretend you made a PInvoke or COM+ call to C++ method that require an integer
        return customFlag;
    }

    public enum TestEnum
    {
        Test1 = 1,
        Test2 = 2,
        Test3 = 3
    }
}

public static class EnumExtensions
{
    public static T GetValue<T>(this Enum enumeration)
    {
        T result = default(T);

        try
        {
            result = (T)Convert.ChangeType(enumeration, typeof(T));
        }
        catch (Exception ex)
        {
            Debug.Assert(false);
            Debug.WriteLine(ex);
        }

        return result;
    }
}    
 10
Author: Doug,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-27 01:30:47
public enum QuestionType
{
    Role = 2,
    ProjectFunding = 3,
    TotalEmployee = 4,
    NumberOfServers = 5,
    TopBusinessConcern = 6
}

...jest dobrą deklaracją.

Musisz oddać wynik do int w ten sposób:

int Question = (int)QuestionType.Role

W Przeciwnym Razie, typ jest nadal QuestionType.

Ten poziom ścisłości jest sposobem C#.

Alternatywą jest użycie zamiast niej deklaracji klasy:

public class QuestionType
{
    public static int Role = 2,
    public static int ProjectFunding = 3,
    public static int TotalEmployee = 4,
    public static int NumberOfServers = 5,
    public static int TopBusinessConcern = 6
}

Jest mniej elegancki w deklarowaniu, ale nie musisz go umieszczać w kodzie:

int Question = QuestionType.Role

Alternatywnie możesz czuć się bardziej komfortowo z Visual Basic, który zaspokaja tego typu oczekiwania w wielu miejsca.

 9
Author: Knickerless-Noggins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-27 17:07:43

Możesz to zrobić implementując metodę rozszerzenia do zdefiniowanego typu enum:

public static class MyExtensions
{
    public static int getNumberValue(this Question questionThis)
    {
        return (int)questionThis;
    }
}

To upraszcza uzyskanie wartości int bieżącej wartości enum:

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

Lub

int value = Question.Role.getNumberValue();
 7
Author: Bronek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-09 22:51:24
int number = Question.Role.GetHashCode();

number powinien mieć wartość 2.

 7
Author: JaimeArmenta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-27 12:26:37

Może zamiast metody rozszerzenia:

public static class ExtensionMethods
{
    public static int IntValue(this Enum argEnum)
    {
        return Convert.ToInt32(argEnum);
    }
}

A użycie jest nieco ładniejsze:

var intValue = Question.Role.IntValue();
 6
Author: SixOThree,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-21 02:51:42

My fav hack with int or smaller enums:

GetHashCode();

Dla enum

public enum Test
{
    Min = Int32.MinValue,
    One = 1,
    Max = Int32.MaxValue,
}

To

var values = Enum.GetValues(typeof(Test));

foreach (var val in values) 
{
    Console.WriteLine(val.GetHashCode());
    Console.WriteLine(((int)val));
    Console.WriteLine(val);
}

Wyjścia

one
1
1  
max
2147483647
2147483647    
min
-2147483648
-2147483648    

Zastrzeżenie: Nie działa na enumach opartych na long

 3
Author: Erik Karlsson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-17 13:47:15

Poniżej znajduje się metoda rozszerzenia

public static string ToEnumString<TEnum>(this int enumValue)
        {
            var enumString = enumValue.ToString();
            if (Enum.IsDefined(typeof(TEnum), enumValue))
            {
                enumString = ((TEnum) Enum.ToObject(typeof (TEnum), enumValue)).ToString();
            }
            return enumString;
        }
 2
Author: Kamran Shahid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-16 06:58:06

Najprostszym rozwiązaniem, jakie przychodzi mi do głowy, jest przeciążenie metody Get(int) w ten sposób:

[modifiers] Questions Get(Question q)
{
    return Get((int)q);
}

Gdzie [modifiers] może być ogólnie takie samo jak dla metody Get(int). Jeśli nie możesz edytować klasy Questions lub z jakiegoś powodu nie chcesz, możesz przeciążyć metodę pisząc rozszerzenie:

public static class Extensions
{
    public static Questions Get(this Questions qs, Question q)
    {
        return qs.Get((int)q);
    }
}
 1
Author: Grx70,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-28 14:09:43

Spróbuj tego zamiast Konwertuj enum na int:

public static class ReturnType
{
    public static readonly int Success = 1;
    public static readonly int Duplicate = 2;
    public static readonly int Error = -1;        
}
 1
Author: Nalan Madheswaran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-14 20:28:07

Przykład, który chciałbym zasugerować 'aby uzyskać wartość' int 'z enum to,'

public enum Sample
{Book =1, Pen=2, Pencil =3}

int answer = (int)Sample.Book;

Teraz odpowiedź będzie 1.

Mam nadzieję, że to komuś pomoże.
 1
Author: Vivek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-03 07:12:01

W Vb. Powinno być

Public Enum Question
    Role = 2
    ProjectFunding = 3
    TotalEmployee = 4
    NumberOfServers = 5
    TopBusinessConcern = 6
End Enum

Private value As Integer = CInt(Question.Role)
 1
Author: VPP,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-12 07:09:30

Ponieważ enums może być zadeklarowany z wieloma typami prymitywnymi, użyteczna może być ogólna metoda rozszerzenia do oddania dowolnego typu enum.

        enum Box
        {
            HEIGHT,
            WIDTH,
            DEPTH
        }

        public static void UseEnum()
        {
            int height = Box.HEIGHT.GetEnumValue<int>();
            int width = Box.WIDTH.GetEnumValue<int>();
            int depth = Box.DEPTH.GetEnumValue<int>();
        }

        public static T GetEnumValue<T>(this object e) => (T)e;
 1
Author: Jeffrey Ferreiras,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-06 05:14:37
public enum Suit : int
{
    Spades = 0,
    Hearts = 1,
    Clubs = 2,
    Diamonds = 3
}

Console.WriteLine((int)(Suit)Enum.Parse(typeof(Suit), "Clubs"));

//from int
Console.WriteLine((Suit)1);

//From number you can also
Console.WriteLine((Suit)Enum.ToObject(typeof(Suit), 1));

if (typeof(Suit).IsEnumDefined("Spades"))
{
    var res = (int)(Suit)Enum.Parse(typeof(Suit), "Spades");
    Console.Out.WriteLine("{0}", res);
}
 1
Author: Gauravsa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-27 06:29:29

Spróbuj tego:

int value = YourEnum.ToString("D");
 -14
Author: Caryn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-23 07:47:58