我要如何转换的System.Type其空的version? [英] How do I convert a System.Type to its nullable version?
本文介绍了我要如何转换的System.Type其空的version?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
再次其中之一:有没有做我的助手方法的东西,而不是一个简单的内置的方式吗?
Once again one of those: "Is there an easier built-in way of doing things instead of my helper method?"
所以它很容易从一个可空类型的基础类型,但我怎么得到.NET类型的可空版本?
So it's easy to get the underlying type from a nullable type, but how do I get the nullable version of a .NET type?
所以,我有
typeof(int)
typeof(DateTime)
System.Type t = something;
和我想
int?
DateTime?
或
Nullable<int> (which is the same)
if (t is primitive) then Nullable<T> else just T
有一个内置的方法?
Is there a built-in method?
推荐答案
下面是code我用:
Type GetNullableType(Type type) {
// Use Nullable.GetUnderlyingType() to remove the Nullable<T> wrapper if type is already nullable.
type = Nullable.GetUnderlyingType(type);
if (type.IsValueType)
return typeof(Nullable<>).MakeGenericType(type);
else
return type;
}
编辑:原code有一个错误的地方会意外行为,如果键入
本身就是一个可空&LT; T&GT;
。
这篇关于我要如何转换的System.Type其空的version?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文