Comprobar si la instancia de tipo es una enumeración anulable en C#


¿Cómo puedo comprobar si un Tipo es una enumeración nullable en C# algo así como

Type t = GetMyType();
bool isEnum = t.IsEnum; //Type member
bool isNullableEnum = t.IsNullableEnum(); How to implement this extension method?
Author: adrin, 2010-04-27

5 answers

public static bool IsNullableEnum(this Type t)
{
    Type u = Nullable.GetUnderlyingType(t);
    return (u != null) && u.IsEnum;
}
 140
Author: LukeH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-27 16:47:47

EDITAR: Voy a dejar esta respuesta ya que funcionará, y demuestra algunas llamadas que los lectores podrían no conocer de otra manera. Sin embargo, La respuesta de Lucas es definitivamente más agradable - vote :)

Puedes hacer:

public static bool IsNullableEnum(this Type t)
{
    return t.IsGenericType &&
           t.GetGenericTypeDefinition() == typeof(Nullable<>) &&
           t.GetGenericArguments()[0].IsEnum;
}
 40
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:07

A partir de C# 6.0 la respuesta aceptada se puede refactorizar como

Nullable.GetUnderlyingType(t)?.IsEnum == true

El = = true es necesario para convertir bool? to bool

 6
Author: Bigjim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-12 13:28:09
public static bool IsNullable(this Type type)
{
    return type.IsClass
        || (type.IsGeneric && type.GetGenericTypeDefinition == typeof(Nullable<>));
}

Omití la verificación IsEnum que ya hiciste, ya que eso hace que este método sea más general.

 1
Author: Bryan Watts,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-27 16:36:02
 1
Author: Daniel Renshaw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-27 16:36:49