C# 如何从类型对象获取可为空的类型对象
实施此方法的最佳方式是什么:C# 如何从类型对象获取可为空的类型对象,c#,.net,C#,.net,实施此方法的最佳方式是什么: Type GetNullableTypeFromType(Type tp); 所以 Type tpString = GetNullableTypeFromType(typeof(string)); // Returns typeof(string) Type tpInt = GetNullableTypeFromType(typeof(int)); // Returns typeof(int?) 公共静态类型GetNullableType(类型t) {
Type GetNullableTypeFromType(Type tp);
所以
Type tpString = GetNullableTypeFromType(typeof(string)); // Returns typeof(string)
Type tpInt = GetNullableTypeFromType(typeof(int)); // Returns typeof(int?)
公共静态类型GetNullableType(类型t)
{
if(t.IsValueType&(null.getUnderlineType(t)==null))
返回typeof(可为空)。MakeGenericType(t);
其他的
返回t;
}
公共静态类型GetNullableType(类型t)
{
if(t.IsValueType&(null.getUnderlineType(t)==null))
返回typeof(可为空)。MakeGenericType(t);
其他的
返回t;
}
我会在两行之间添加这个选项,这样GetNullableType(typeof(int?)
就可以工作了(returnint?
):否则如果(t.IsGenericType&&t.GetGenericTypeDefinition()==typeof(Nullable))返回t代码>。同样,传递typeof(Nullable)
将返回相同的类型。如果传递接口,仍然会失败。通过将方法体更改为如下内容,可以使其更加健壮:if(t.IsValueType&&(Nullable.getUnderlineType(t)==null))返回typeof(Nullable.MakeGenericType(t);返回t代码>另一个我没有考虑过的案例。根据建议更新代码;比检查所有不返回Nullable的情况要干净得多。:-)我想在您的两行之间添加它,以便GetNullableType(typeof(int?)
可以工作(returnint?
):否则如果(t.IsGenericType&&t.GetGenericTypeDefinition()==typeof(Nullable))返回t代码>。同样,传递typeof(Nullable)
将返回相同的类型。如果传递接口,仍然会失败。通过将方法体更改为如下内容,可以使其更加健壮:if(t.IsValueType&&(Nullable.getUnderlineType(t)==null))返回typeof(Nullable.MakeGenericType(t);返回t代码>另一个我没有考虑过的案例。根据建议更新代码;比检查所有不返回Nullable的情况要干净得多。:-)
public static Type GetNullableType(Type t)
{
if (t.IsValueType && (Nullable.GetUnderlyingType(t) == null))
return typeof(Nullable<>).MakeGenericType(t);
else
return t;
}