Skip to main content
 首页 » 编程设计

c#之通过 HasValue = false 的反射创建 Nullable,仅给定类型为 `Type` 的参数

2024年02月06日17itcoder

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

换句话说,完成这段代码:

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

我的尝试无效(它抛出 NullReferenceException),因为没有默认构造函数:

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

请您参考如下方法:

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

如果您想要一个签名为 object 的方法, 你只要返回 null :

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

这将始终是任何可空类型值的盒装表示形式,其中 HasValue一片空白。换句话说,该方法毫无意义......你还不如使用 null文字:

var i = (int?) null; 

当然,如果type不保证是可为空的值类型,您可能希望对代码进行条件化...但重要的是要了解不存在 Nullable<T> 的对象 表示形式。值(value)。即使对于非 null 值,装箱表示也是 non-nullable 类型的装箱表示:

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