无法将T value1与T value2 = default(T)进行比较.为什么以及如何在C#上做到这一点?

Gir*_*rdi 7 c# comparison types

我正在尝试以下方法:

T value1 = el.value; // it's of type T already
T value2 = default(T);
if (value1 != value2) // gives the following error: Operator '!=' cannot be applied to operands of type 'T' and 'T'
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

那么,我怎么能比较这两个值呢?为什么会出现这种错误?

提前致谢!

Jon*_*eet 12

您可以使用where T : IEquatable<T>Henk提到的约束,或忽略约束并使用:

if (!EqualityComparer<T>.Default.Equals(value1, value2))
Run Code Online (Sandbox Code Playgroud)