C#比较两个通用值 [英] c# compare two generic values

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

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/390900/cant-operator-be-applied-to-generic-types-in-c\">Can’t ==操作符在C#中被应用到泛型类型?

我有codeD是这样的:

I've coded something like this:

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

    return (valueInDB != valueFromView);
}

现在的功能不会错误编译的运算符'!='不能应用于类型为'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 ?

推荐答案

您不能使用泛型类型的运营商(除富== null,其特殊的套管),除非你加入其中T:类以表明它是引用类型(那么Foo就==酒吧是合法的)

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&LT; T&GT; .DEFAULT来为你做它。这将不会在工种,只为==提供一个操作符重载也没有任何:

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&LT; T&GT;

  • 重写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&LT; T&GT; 然后用值类型使用,如果他们不执行,当EqualityComparer默认故障可能会导致拳击 IEquatable&LT; T&GT; (如果你控制正在使用,这可能不是问题的类型)。我假设你正在使用=!性能虽然如此限制的泛型类型将避免偶然通过的Object.Equals拳(对象)的路线。

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天全站免登陆