Nullable generic field in generic class

僤鯓⒐⒋嵵緔 提交于 2019-12-12 17:13:15

问题


I'm trying to do something like this:

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

Is this possible?

This gives me the error:

error CS0453: The type T' must be a non-nullable value type in order to use it as type parameterT' in the generic type or method System.Nullable'.

Thanks


回答1:


Add where T : struct generic constraint to get rid of the error since Nullable<T> accepts only struct.

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

Nullable<T> is defined as below

public struct Nullable<T> where T : struct

So you're also forced to do so, just to prevent you from doing MySuperCoolClass<object> which makes object? which is not valid.




回答2:


Do you see your job ?

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;
}


来源:https://stackoverflow.com/questions/20353742/nullable-generic-field-in-generic-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!