Test for equality to the default value

可紊 提交于 2020-07-31 07:50:17

问题


The following doesn't compile:

public void MyMethod<T>(T value)
{
    if (value == default(T))
    {
        // do stuff
    }
}

Error: Operator '==' cannot be applied to operands of type 'T' and 'T'

I can't use value == null because T may be a struct.
I can't use value.Equals(default(T)) because value may be null.
What is the proper way to test for equality to the default value?


回答1:


To avoid boxing for struct / Nullable<T>, I would use:

if (EqualityComparer<T>.Default.Equals(value,default(T)))
{
    // do stuff
}

This supports any T that implement IEquatable<T>, using object.Equals as a backup, and handles null etc (and lifted operators for Nullable<T>) automatically.

There is also Comparer<T>.Default which handles comparison tests. This handles T that implement IComparable<T>, falling back to IComparable - again handling null and lifted operators.




回答2:


What about

object.Equals(value, default(T))


来源:https://stackoverflow.com/questions/1895761/test-for-equality-to-the-default-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!