聪明的方法找到相应的可空类型?

Mar*_*tke 0 c# reflection types nullable

我怎么能避免这个字典(或动态创建它)?

Dictionary<Type,Type> CorrespondingNullableType = new Dictionary<Type, Type>
{
    { typeof(bool),    typeof(bool?) },
    { typeof(byte),    typeof(byte?) },
    { typeof(sbyte),   typeof(sbyte?) },
    { typeof(char),    typeof(char?) },
    { typeof(decimal), typeof(decimal?) },
    { 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?) },
};
Run Code Online (Sandbox Code Playgroud)

the*_*oop 5

你想做的事情如下:

Type structType = typeof(int);    // or whatever type you need
Type nullableType = typeof(Nullable<>).MakeGenericType(structType);
Run Code Online (Sandbox Code Playgroud)

获取Nullable<T>给定T 的对应值(在此示例中int)