繁体   English   中英

仅给定类型为Type的参数,通过HasValue = false的反射可空创建

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

给定类型参数为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]);
}

给定类型参数为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是可为空的值类型,则可能需要对代码进行条件化……但重要的是要了解,不存在诸如Nullable<T>值的对象表示之类的东西。 即使对于非空值,装箱的表示形式也是非空类型的装箱的表示形式:

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

高度危险 (建议不要将其用于非测试目的)是使用SharpUtils的方法UnsafeTools.Box<T>(T? nullable) 它绕过可为空的类型的常规装箱,该装箱将其值装箱或返回null,而是创建一个Nullable<T>的实际实例。 请注意,使用这样的实例可能会遇到很多问题。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM