NULLABLE通过带的HasValue =虚假反射创建,给定类型Type`的`参数只 [英] Nullable create via reflection with HasValue = false, given a parameter of type `Type` only

查看:219
本文介绍了NULLABLE通过带的HasValue =虚假反射创建,给定类型Type`的`参数只的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个类型的参数,它是一个可空<> ,我怎么能创建该类型具有的一个实例的HasValue =虚假



在换句话说,完成这个代码:

  //类型是保证实现可空<> 
公共静态对象创建(type类型)
{
//实例可空< T>与反思其的HasValue =虚假的,并返回
}



我的企图,它没有按' ŧ工作(它抛出一个的NullReferenceException ),因为没有默认的构造函数:

 静态无效的主要(字串[] args)
{
Console.WriteLine(创建(typeof运算(可空< INT>)));

到Console.ReadLine();
}

//类型是保证从可空<落实;>
公共静态对象创建(type类型)
{
// Instantatie可空< T>与反思其的HasValue =虚假的,并返回
返回type.GetConstructor(新类型[0])调用(新对象[0]​​)。
}


解决方案

给定一个类型的参数,它是一个可空<> ,我怎么可以创建一个类型,它具有的HasValue =虚假


的一个实例<? /块引用>

如果你想与对象,你只返回一个签名的方法

  //类型是保证从可空<落实;> 
公共静态对象创建(type类型)
{
返回NULL;
}

这将永远是任何可空类型值,其中<$ C的盒装表示$ C>的HasValue 为空。换句话说,该方法是没有意义的......你可能也仅仅使用文字:

  VAR I =(INT?)空; 



当然,如果键入不是保证是空值类型,你可能要条件化的代码......但要明白,有因为没有这样的事情是很重要的一个的对象的一个可空<的代表性; T> 值。即使对于非空值,盒装表示是的非空的的类型的盒装表示:

 诠释? X = 5; 
对象Y = X; //拳击
Console.WriteLine(y.GetType()); // System.Int32;空性已经消失


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

In other words, complete this code:

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

My attempt, which doesn't work (it throws a NullReferenceException) as there's no default constructor:

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?

If you want a method with a signature of object, you just return null:

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

That will always be the boxed representation of any nullable type value where HasValue is null. In other words, the method is pointless... you might as well just use the null literal:

var i = (int?) null;

Of course, if type isn't guaranteed to be nullable value type, you might want to conditionalize the code... but it's important to understand that there's no such thing as an object representation of a Nullable<T> value. Even for non-null values, the boxed representation is the boxed representation of the non-nullable type:

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

这篇关于NULLABLE通过带的HasValue =虚假反射创建,给定类型Type`的`参数只的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆