Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从类型对象获取可为空的类型对象_C#_.net - Fatal编程技术网

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?)
就可以工作了(return
int?
):
否则如果(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?)
可以工作(return
int?
):
否则如果(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;
}