Pregunta

Estoy tratando de hacer algo como esto:

public class MySuperCoolClass<T>
{
    public T? myMaybeNullField {get; set;}
}

es posible?

Esto me da el error:

Error CS0453: el tipo T' must be a non-nullable value type in order to use it as type parameterT 'En el tipo o sistema de método genérico.

Gracias

¿Fue útil?

Solución

Agregar where T : struct restricción genérica para deshacerse del error desde Nullable<T> Acepta solo struct.

public class MySuperCoolClass<T> where T : struct
{
    public T? myMaybeNullField { get; set; }
}

Nullable<T> se define como a continuación

public struct Nullable<T> where T : struct

Entonces también te ves obligado a hacerlo, solo para evitar que hagas MySuperCoolClass<object> que hace object? que no es válido.

Otros consejos

¿Ves tu trabajo?

public static Nullable<T> ToNullable<T>(this string s) where T: struct
{
    Nullable<T> result = new Nullable<T>();
    try
    {
        if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0)
        {
            TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
            result = (T)conv.ConvertFrom(s);
        }
    }
    catch { } 
    return result;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top