c# 比较两个泛型值 [英] c# compare two generic values

查看:33
本文介绍了c# 比较两个泛型值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
在 C# 中不能将运算符 == 应用于泛型类型吗?

我已经编写了这样的代码:

I've coded something like this:

public bool IsDataChanged()
{           
    T value1 = GetValue2;
    T value2 = GetValue1();

    return (valueInDB != valueFromView);
}

现在该函数无法编译并出现错误Operator '!=' 不能应用于类型为 'T' 和 'T' 的操作数".我需要做什么才能使此功能正常工作?

Right now the function doesn't compile with the error "Operator '!=' cannot be applied to operands of type 'T' and 'T'". What do I have to do to make this function work ?

推荐答案

你不能在泛型类型上使用运算符(除了 foo == null 是特殊情况),除非你添加 where T : class 来表明它是一个引用类型(然后 foo == bar 是合法的)

You cannot use operators on generic types (except for foo == null which is special cased) unless you add where T : class to indicate it is a reference type (then foo == bar is legal)

使用 EqualityComparer.默认为您做.这将适用于只为 == 提供运算符重载的类型,而没有:

Use EqualityComparer<T>.Default to do it for you. This will not work on types which only supply an operator overload for == without also either:

  • 实现IEquatable
  • 覆盖 object.Equals()

一般来说,实现 == 操作符而不至少执行其中一个操作将是一个非常糟糕的主意,因此这不太可能成为问题.

In general implementing the == operator and not also doing at least one of these would be a very bad idea anyway so this is not likely to be an issue.

public bool IsDataChanged<T>()
{           
    T value1 = GetValue2;
    T value2 = GetValue1();

    return !EqualityComparer<T>.Default.Equals(value1 , value2);
}

如果您不限制为 IEquatable,那么 EqualityComparer 默认回退在与值类型一起使用时可能会导致装箱,如果它们没有实现 IEquatable (如果您控制正在使用的类型,这可能无关紧要).我假设您正在使用 =!为了性能,尽管如此限制到 Generic 类型将避免通过 Object.Equals(object) 路由意外装箱.

If you do not restrict to IEquatable<T> then the EqualityComparer default fallback may cause boxing when used with value types if they do not implement IEquatable<T> (if you control the types which are being used this may not matter). I am assuming you were using =! for performance though so restricting to the Generic type will avoid accidental boxing via the Object.Equals(object) route.

这篇关于c# 比较两个泛型值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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