Domanda

Sto cercando di fare qualcosa del genere:

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

È possibile?

Questo mi dà l'errore:

Errore CS0453: il tipo T' must be a non-nullable value type in order to use it as type parameterT 'nel tipo generico o nel metodo System.nulllable'.

Grazie

È stato utile?

Soluzione

Aggiungere where T : struct vincolo generico per sbarazzarsi dell'errore da allora Nullable<T> accetta solo struct.

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

Nullable<T> è definito come di seguito

public struct Nullable<T> where T : struct

Quindi sei anche costretto a farlo, solo per impedirti di farlo MySuperCoolClass<object> che rende object? che non è valido.

Altri suggerimenti

Vedi il tuo lavoro?

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;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top