c# – 如何将非可空类型转换为可空类型?
发布时间:2020-12-16 00:18:01 所属栏目:百科 来源:网络整理
导读:是否可以将仅在运行时知道的非可空值类型转换为可空?换一种说法: public Type GetNullableType(Type t){ if (t.IsValueType) { return typeof(Nullablet); } else { throw new ArgumentException(); }} 显然返回线会出错.有没有办法做到这一点? Type.Make
是否可以将仅在运行时知道的非可空值类型转换为可空?换一种说法:
public Type GetNullableType(Type t) { if (t.IsValueType) { return typeof(Nullable<t>); } else { throw new ArgumentException(); } } 显然返回线会出错.有没有办法做到这一点? Type.MakeGenericType方法看起来很有希望,但我不知道如何获得表示Nullable< T>的未指定的泛型Type对象.有任何想法吗? 解决方法
你想要typeof(Nullable<>).MakeGenericType(t)
注意:Nullable<>没有任何提供的参数是未绑定的泛型类型;对于更复杂的示例,您可以添加逗号以适应 – 即KeyValuePair<,>,Tuple<,>等等 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |