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

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

问题描述

如何检查给定对象是否可为空,换句话说,如何实现以下方法...

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 reference 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 现在引用 bool (System.Boolean) 类型的对象,其值等于 true.我真正想要的是 Nullable

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.

推荐答案

有两种可空类型 - Nullable 和引用类型.

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

Jon 纠正我说如果装箱很难获得类型,但你可以使用泛型:- 那么下面呢.这实际上是在测试类型 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.

Microsoft 文档:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/how-to-identify-a-nullable-type

Microsoft documentation: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/how-to-identify-a-nullable-type

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

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