Detecting a Nullable Type via reflection

前端 未结 5 516
天命终不由人
天命终不由人 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:26

    Well firstly, Nullable is a struct, so there isn't an object as such. You can't call GetType(), as that will box the value (at which point you either get null and thus an exception, or a boxed non-nullable value and therefore not the type you want).

    (Boxing is what's messing up your assertion here - I would assume that IsType accepts object.)

    You can use type inference though to get the type of the variable as a type parameter:

    public bool IsNullable(T value)
    {
        return Nullable.GetUnderlyingType(typeof(T)) != null;
    }
    

    That's not a huge amount of use when you know the exact type at compile-time as in your example, but it's useful for generics. (There are alternative ways of implementing it, of course.)

    What's your real life situation? I assume it's not an assertion like this, given that you know the answer to this one at compile time.

提交回复
热议问题