开发者

Smart way to find the corresponding nullable type?

How could I avoid this dictionary (or create it dynamically)?

Dictionary<Type,Type> CorrespondingNullableType = new Dictionary<Type, Type>
{
    { typeof(bool),    typeof(bool?) },
    { typeof(byte),    typeof(byte?) },
    { typeof(sbyte),   typeof(sbyte?) },
    { typeof(cha开发者_运维知识库r),    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?) },
};


You want to do something like:

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

To get the corresponding Nullable<T> for a given T (in this example, int)


Use a simple generics method:

public Type GetNullable<T>() where T : struct
{
  return typeof(Nullable<T>);
}

This should return the nullable type for any type you pass in.


type? is just syntactic sugar for Nullable<type>

Knowing this, you can then do something like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜