Forma correcta de comprobar si un tipo es Nullable [duplicate]


Esta pregunta ya tiene una respuesta aquí:

Para comprobar si un Type ( propertyType ) es nullable, estoy usando:

bool isNullable =  "Nullable`1".Equals(propertyType.Name)

¿Hay alguna manera de evitar el uso de cuerdas mágicas ?

Author: Felice Pollano, 2012-01-20

2 answers

Absolutamente uso Nullable.GetUnderlyingType:

if (Nullable.GetUnderlyingType(propertyType) != null)
{
    // It's nullable
}

Tenga en cuenta que esto utiliza la clase estática no genéricaSystem.Nullable en lugar de la estructura genérica Nullable<T>.

También tenga en cuenta que esto comprobará si representa un tipo de valor específico (cerrado) nullable... no funcionará si lo usas en un tipo genérico , por ejemplo,

public class Foo<T> where T : struct
{
    public Nullable<T> Bar { get; set; }
}

Type propertyType = typeof(Foo<>).GetProperty("Bar").PropertyType;
// propertyType is an *open* type...
 262
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
2012-01-20 10:27:52

Utilice el siguiente código para determinar si un objeto Type representa un tipo Nullable. Recuerde que este código siempre devuelve false si el objeto Type fue devuelto desde una llamada a GetType.

if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {…}

Explicado en el siguiente enlace MSDN:

Http://msdn.microsoft.com/en-us/library/ms366789.aspx

Además, hay una discusión similar en este SO QA:

¿Cómo comprobar si un objeto es nullable?

 27
Author: VS1,
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:34:41