如何检查对象是否为空的? [英] How to check if an object is nullable?

查看:160
本文介绍了如何检查对象是否为空的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何检查,如果给定对象可为空,换句话说如何实现下面的方法...

How do I check if a given object is nullable in other words how to implement the following method...

bool IsNullableValueType(object o)
{
    ...
}

编辑:我在寻找空值类型。我没有裁判的类型记在心里。

I am looking for nullable value types. I didn't have ref types in mind.

//Note: This is just a sample. The code has been simplified 
//to fit in a post.

public class BoolContainer
{
	bool? myBool = true;
}

var bc = new BoolContainer();

const BindingFlags bindingFlags = BindingFlags.Public
						| BindingFlags.NonPublic
						| BindingFlags.Instance
						;


object obj;
object o = (object)bc;

foreach (var fieldInfo in o.GetType().GetFields(bindingFlags))
{
	obj = (object)fieldInfo.GetValue(o);
}

现在OBJ是指类型的对象布尔(<$ C C $>可选System.Boolean )与价值等于。我真正想要的是类型的对象可空&LT;布尔&GT;

obj now refers to an object of type bool (System.Boolean) with value equal to true. What I really wanted was an object of type Nullable<bool>

所以,现在作为一个变通,我决定检查如果o可为空,并创建一个围绕OBJ一个可空包装。

So now as a work around I decided to check if o is nullable and create a nullable wrapper around obj.

推荐答案

有两种类型的可空 - 可空&LT; T&GT; 和引用类型

There are two types of nullable - Nullable<T> and reference-type.

乔恩纠正我,这是很难得的类型,如果盒装的,但是你可以用仿制药:   - 所以怎么样在下面。这实际上是测试类型 T ,但使用 OBJ 纯粹是为了泛型类型推断(以方便调用参数) - 这是可行的,几乎没有相同的 OBJ 参数,但

Jon has corrected me that it is hard to get type if boxed, but you can with generics: - so how about below. This is actually testing type T, but using the obj parameter purely for generic type inference (to make it easy to call) - it would work almost identically without the obj param, though.

static bool IsNullable<T>(T obj)
{
    if (obj == null) return true; // obvious
    Type type = typeof(T);
    if (!type.IsValueType) return true; // ref-type
    if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable<T>
    return false; // value-type
}

不过,这是行不通的这么好,如果你已经装箱的值对象变量。

But this won't work so well if you have already boxed the value to an object variable.

这篇关于如何检查对象是否为空的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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