测试是否等于默认值
以下内容无法编译:
public void MyMethod<T>(T value)
{
if (value == default(T))
{
// do stuff
}
}
错误:运算符'=='无法应用于类型'T'和'T'的操作数
Error: Operator '==' cannot be applied to operands of type 'T' and 'T'
我不能使用 value == null
,因为 T
可能是一个结构。
我不能使用 value.Equals(default(T))
因为 value
可能为 null
。
什么是测试与否相等的正确方法?
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?
以避免为 struct
装箱/ Nullable< T>
,我会使用:
To avoid boxing for struct
/ Nullable<T>
, I would use:
if (EqualityComparer<T>.Default.Equals(value,default(T)))
{
// do stuff
}
这支持任何实现 IEquatable< T> $ c $的
T
c>,使用 object.Equals
作为备份,并处理 null
等(并取消了自动为Nullable
)。
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.
还有 Comparer< T>。默认
处理比较测试。这处理实现 IComparable< T>
的 T
,回退到 IComparable
-再次处理 null
并取消了运算符。
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.