Nullable create via reflection with HasValue = false, given a parameter of type `Type` only

后端 未结 2 697
别跟我提以往
别跟我提以往 2021-01-25 04:02

Given a type parameter which is a Nullable<>, how can I create an instance of that type which has HasValue = false?

In other words, compl

2条回答
  •  隐瞒了意图╮
    2021-01-25 05:01

    Highly dangerous (and not recommended for non-testing purposes) is to use SharpUtils' method UnsafeTools.Box(T? nullable). It bypasses the normal boxing of nullable types, which boxes their value or returns null, and instead creates an actual instance of Nullable. Note that working with such an instance can be extremely buggy.

    public static object Create() where T : struct //T must be a normal struct, not nullable
    {
        return UnsafeTools.Box(default(T?));
    }
    

提交回复
热议问题