Nullable通过HasValue = false的reflection创建,仅给出类型为“Type”的参数

给定一个Nullable的类型参数,如何创建具有HasValue = false的该类型的实例?

换句话说,填写此代码:

 //type is guaranteed to implement Nullable public static object Create(Type type) { //Instantiate a Nullable with reflection whose HasValue = false, and return it } 

我的尝试,它不起作用(它抛出NullReferenceException ),因为没有默认的构造函数:

 static void Main(string[] args) { Console.WriteLine(Create(typeof(Nullable))); Console.ReadLine(); } //type is guaranteed to be implement from Nullable public static object Create(Type type) { //Instantatie a Nullable with reflection whose HasValue = false, and return it return type.GetConstructor(new Type[0]).Invoke(new object[0]); } 

给定一个Nullable<>的类型参数,如何创建具有HasValue = false的该类型的实例?

如果你想要一个带有签名object的方法,你只需返回null

 //type is guaranteed to be implement from Nullable<> public static object Create(Type type) { return null; } 

这将始终是HasValue为null的任何可空类型值的盒装表示。 换句话说,这个方法毫无意义……你也可以使用null文字:

 var i = (int?) null; 

当然,如果type不能保证是可以为null的值类型,你可能想要条件化代码……但重要的是要理解没有Nullable值的对象表示。 即使对于非空值,盒装表示也是非可空类型的盒装表示:

 int? x = 5; object y = x; // Boxing Console.WriteLine(y.GetType()); // System.Int32; nullability has vanished 

非常危险 (并且不建议用于非测试目的)是使用SharpUtils的方法UnsafeTools.Box(T? nullable) 。 它绕过了可空类型的正常装箱,它将它们的值装箱或返回null,而是创建一个Nullable的实际实例。 请注意,使用此类实例可能非常错误。

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