不能以T VALUE2 =默认(T)比较牛逼值1。为什么以及如何做到这一点的C#? [英] Can't compare T value1 with T value2 = default(T). Why and how to do that on C#?

查看:197
本文介绍了不能以T VALUE2 =默认(T)比较牛逼值1。为什么以及如何做到这一点的C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以下内容:

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'
{
    // ...
}

所以,怎么可能我比较这两个值?而为什么这个错误发生?

So, how could I compare both values? And why do this error occur?

在此先感谢!

推荐答案

您可以使用,其中T的约束:IEquatable< T> 为亨克提到的,或忽略约束和用途:

You can either use a constraint of where T : IEquatable<T> as Henk mentioned, or ignore constraints and use:

if (!EqualityComparer<T>.Default.Equals(value1, value2))

这篇关于不能以T VALUE2 =默认(T)比较牛逼值1。为什么以及如何做到这一点的C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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