Detecting a Nullable Type via reflection

前端 未结 5 521
天命终不由人
天命终不由人 2021-01-01 12:14

Surprisingly the following code fails the Assert:

int? wtf = 0;
Assert.IsType>(wtf);

So just out curiosity, how c

5条回答
  •  渐次进展
    2021-01-01 12:46

    I like the @jon-skeet answer but it only works if you know the type you are testing against. In our world we are using reflection to open up objects and test values against regex expressions.

    simplifying the extension to work for any type worked better for us.

    public static bool IsNullable(this Type type)
    {
        return Nullable.GetUnderlyingType(type) != null;
    }
    

    generics are life's blood but sometimes... :)

提交回复
热议问题