C# 找到相应的可空类型的智能方法?

C# 找到相应的可空类型的智能方法?,c#,reflection,types,nullable,C#,Reflection,Types,Nullable,如何避免使用此词典(或动态创建) 字典对应的NullableType=新字典 { {typeof(bool),typeof(bool?}, {typeof(byte),typeof(byte?}, {typeof(sbyte),typeof(sbyte?}, {typeof(char),typeof(char?}, {typeof(十进制),typeof(十进制?}, {typeof(double),typeof(double?}, {typeof(float),typeof(float?},

如何避免使用此词典(或动态创建)

字典对应的NullableType=新字典
{
{typeof(bool),typeof(bool?},
{typeof(byte),typeof(byte?},
{typeof(sbyte),typeof(sbyte?},
{typeof(char),typeof(char?},
{typeof(十进制),typeof(十进制?},
{typeof(double),typeof(double?},
{typeof(float),typeof(float?},
{typeof(int),typeof(int?},
{typeof(uint),typeof(uint?},
{typeof(long),typeof(long?},
{typeof(ulong),typeof(ulong?},
{typeof(short),typeof(short?},
{typeof(ushort),typeof(ushort?},
{typeof(Guid),typeof(Guid?},
};

类型?
只是
可空的

知道了这一点,你就可以这样做:

public Type GetNullableType(Type t) => typeof(Nullable<>).MakeGenericType(t);
public类型GetNullableType(类型t)=>typeof(Nullable);

您希望执行以下操作:

Type structType = typeof(int);    // or whatever type you need
Type nullableType = typeof(Nullable<>).MakeGenericType(structType);
Type structType=typeof(int);//或者任何你需要的类型
Type nullableType=typeof(Nullable).MakeGenericType(structType);

要获取给定T(在本例中为
int
)的相应
Nullable

请使用简单的泛型方法:

public Type GetNullable<T>() where T : struct
{
  return typeof(Nullable<T>);
}
public类型GetNullable(),其中T:struct
{
返回类型(可为空);
}

这将为您传入的任何类型返回可为空的类型。

您能解释一下拥有这样一个字典的原因吗?你想做什么?这是我的第一个想法,但我在编译时没有
T
,只是
System.Type的一个实例。在编译时你不需要T-这就是泛型的奇迹。谢谢,这就是我要找的。
public Type GetNullable<T>() where T : struct
{
  return typeof(Nullable<T>);
}