检查是否给定对象(引用或值类型)等于其默认 [英] Check to see if a given object (reference or value type) is equal to its default

查看:125
本文介绍了检查是否给定对象(引用或值类型)等于其默认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种方法来检查,看看是否一个给定对象的值等于它的默认值。我环顾四周,并拿出这样的:

I'm trying to find a way to check and see if the value of a given object is equal to its default value. I've looked around and come up with this:

    public static bool IsNullOrDefault<T>(T argument)
    {
        if (argument is ValueType || argument != null)
        {
            return object.Equals(argument, default(T));
        }
        return true;
    }



我遇到的问题是,我想这样称呼它:

The problem I'm having is that I want to call it like this:

            object o = 0;
            bool b = Utility.Utility.IsNullOrDefault(o);



是o是一个对象,但我希望把它搞清楚的基本类型和检查默认那价值。的基本类型,在这种情况下,为整数,我想在这种情况下,要知道如果该值等于默认(INT),不是默认(对象)。

Yes o is an object, but I want to make it figure out the base type and check the default value of that. The base type, in this case, is an integer and I want to know in this case if the value is equal to default(int), not default(object).

我开始想,这也许是不可能的。

I'm starting to think this might not be possible.

推荐答案

在你的榜样,你的整数​​是盒装,因此你的 T 将是对象,并对象的默认为空,所以这不是对您有价值。如果对象是一个值类型,你可以得到它的一个实例(这是默认值)作为比较用。是这样的:

In your example, your integer is boxed and therefore your T is going to be object, and the default of object is null, so that's not valuable to you. If the object is a value type, you could get an instance of it (which would be the default) to use as a comparison. Something like:

if (argument is ValueType)
{
   object obj = Activator.CreateInstance(argument.GetType());
   return obj.Equals(argument);
}

您会希望采取这种前处理其他的可能性。的马克Gravell的答案带来了一些好点的考虑,但对于你的方法的完整版,你可能有

You'd want to deal with other possibilities before resorting to this. Marc Gravell's answer brings up some good points to consider, but for a full version of your method, you might have

public static bool IsNullOrDefault<T>(T argument)
{
    // deal with normal scenarios
    if (argument == null) return true;
    if (object.Equals(argument, default(T))) return true;

    // deal with non-null nullables
    Type methodType = typeof(T);
    if (Nullable.GetUnderlyingType(methodType) != null) return false;

    // deal with boxed value types
    Type argumentType = argument.GetType();
    if (argumentType.IsValueType && argumentType != methodType) 
    {
        object obj = Activator.CreateInstance(argument.GetType());
        return obj.Equals(argument);
    }

    return false;
}

这篇关于检查是否给定对象(引用或值类型)等于其默认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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