Forma correcta de comprobar si un tipo es Nullable [duplicate]
Esta pregunta ya tiene una respuesta aquí:
- ¿Cómo comprobar si un objeto es nullable? 13 respuestas
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 ?
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...
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:
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