我正在尝试做这样的事情:

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

这可能吗?

这给了我错误:

错误CS0453:类型 T' must be a non-nullable value type in order to use it as type parametert'在通用类型或方法系统中。

谢谢

有帮助吗?

解决方案

添加 where T : struct 由于 Nullable<T> 仅接受 struct.

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

Nullable<T> 定义如下

public struct Nullable<T> where T : struct

因此,您也被迫这样做,只是为了防止您做 MySuperCoolClass<object> 这使得 object? 这是无效的。

其他提示

你看到你的工作吗?

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;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top