Verifica se un oggetto è un Enum


91

Vorrei sapere se "theObject" è un enum (di qualsiasi tipo di enum)

 foreach (var item in Enum.GetValues(theObject.GetType())) {

     //do something
 }

Risposte:


207

La domanda è la risposta. :)

bool isEnum = theObject is Enum;

14
Lo adoro! E ancora più vicino alla domanda: if (theObject is Enum) {...}
Peter Lillevold,

6
Questo non è nemmeno quello per cui sono venuto qui e ti sto dando un punto. È così ... pulito ... <sniff>, è bellissimo uomo TT
Lukas

13
/ * Test * / if (anObject is / * an * / Enum) {}
Tom Fobear,

bool isEnum = theObject.GetType (). IsEnum; è meglio, Enum non restituisce sempre vero
chris hu

69

Se hai un Type, usa la Type.IsEnumproprietà, ad esempio:

bool isEnum = theObject.GetType().IsEnum;

2
Questo ha funzionato per me. Non sono riuscito a capire come far funzionare la risposta accettata in VB.NET.
Shea Daniels

4
In realtà avevo bisogno di sapere come verificare un Typeessere di tipo Enum. +1
Nathan


2

Per i parametri di tipo generico, il parametro può essere vincolato anziché testato:

where T : Enum
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.