如何解决运算符 '!=' 不能应用于类型为 'T' 和 'T' 的操作数 [英] How to solve Operator '!=' cannot be applied to operands of type 'T' and 'T'

查看:28
本文介绍了如何解决运算符 '!=' 不能应用于类型为 'T' 和 'T' 的操作数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 int 类型,此代码片段按预期工作:

This code snippet works as expected for the int type:

public class Test 
{
    public int Value
    {
        get => _Value;
        set
        {
            if (_Value != value)
                _Value = value;
        }
    }
    private int _Value;
}

int 被泛型 T 替换时,编译器会抱怨:

When int is replaced by the generic T, the compiler complains with:

运算符 '!=' 不能应用于类型为 'T' 和 'T' 的操作数

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

为什么会发生这种情况,有没有办法解决?

Why does this happen and is there a way to solve it?

推荐答案

using System.Collections.Generic;

public class Test<T>
{
    public T Value
    {
         get => _Value; 
         set
         {
            // operator== is undefined for generic T; EqualityComparer solves this
            if (!EqualityComparer<T>.Default.Equals(_Value, value))
            {
                _Value = value;
            }
         }
    }
    private T _Value;
}

这篇关于如何解决运算符 '!=' 不能应用于类型为 'T' 和 'T' 的操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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