简体   繁体   English

常规检查是否为null,而不是默认值(T)

[英]generic check for null, not for default (T)

How can i determine if value of generic method is null? 我如何确定泛型方法的值是否为空? So only way i found is check that it's a class and it has default value. 因此,我发现的唯一方法是检查它是否是一类并且具有默认值。 So my code: 所以我的代码:

    public static string AsJsonArray<T>(this IEnumerable<T> collection)
    {
        var sb = new StringBuilder("[");
        var enumerator = collection.GetEnumerator();
        bool isClass = typeof (T).IsClass;
        if (enumerator.MoveNext())
        {
            if (isClass && enumerator.Current == default(T))
                sb.Append("null");
            else 
                sb.Append(enumerator.Current);
            while (enumerator.MoveNext())
            {
                sb.Append(", ");
                if (isClass && enumerator.Current == default(T))
                    sb.Append("null");
                else
                    sb.Append(enumerator.Current);
            }
        }

        var asJsonArray = sb.Append("]").ToString();
        return asJsonArray;
    }

but i'm really annoyed by this ugly reflection check isClass && enumerator.Current == default(T) 但是我真的很讨厌这个丑陋的反射检查isClass && enumerator.Current == default(T)

Do any alternative exist? 是否有其他选择?

As comments suggest, use the == operator or a ReferenceEquals check. 如注释所示,使用==运算符或ReferenceEquals检查。

private static bool IsNull<T>(T item)
{
   return object.ReferenceEquals(null, item);
}

This yields: 这样产生:

int? nullableInt = null;
Console.WriteLine(IsNull(nullableInt)); //true
object refType = null;
Console.WriteLine(IsNull(refType)); //true
int valueType = 0;
Console.WriteLine(IsNull(valueType)); //false

The IsClass check you do would fail for the Nullable<T> because Nullable is actually a struct . 您所做的IsClass检查对于Nullable<T>将失败,因为Nullable实际上是一个struct

To remove duplicate code you could even create a method to check for null and replace with text: 要删除重复的代码,您甚至可以创建一种方法来检查null并替换为文本:

private static string ToStringOrDefault<T>(T item, string replacement = "null")
{
    return IsNull(item) ? replacement : item.ToString();
}

sb.Append(ToStringOrDefault(nullableInt));

It sounds like you just need == null : 听起来您只需要== null

var current = enumerator.Current;
if (current == null)
{
    sb.Append("null");
}
else
{
    sb.Append(current);
}

Or more compactly: 或更紧凑:

var current = enumerator.Current;
sb.Append(current == null ? (object) "null" : current);

Or even by boxing before the call, and using the null-coalescing operator: 甚至可以通话进行拳击,并使用null-coalescing运算符:

object current = enumerator.Current; // Boxes where necessary
sb.Append(current ?? "null");

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

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