使用比较运算符,如'!='和'==',以约束在C#泛型的价值 [英] Using comparison operators, such as '!=' and '==', with generics constrained as value in C#

查看:548
本文介绍了使用比较运算符,如'!='和'==',以约束在C#泛型的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

class Foo<T> where T : struct
{
    private T t;
    [...]
    public bool Equals(T t) { return this.t == t; }
}

当我尝试编译,它给了我以下错误:

When I try to compile, it gives me the following error:

运营商'=='不能应用于类型为'T'和'T'

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

为什么不能做到?如果约束是其中T:类它会奏效。但我需要它是值类型,因为我在执行这个通用将永远是一个枚举。

Why can't it be done? If the constraint was where T : class it would have worked. But I need it to be value type because in my implementation this generic will always be an enum.

我在做什么,以circunvent的情况是使用的Object.Equals()方法。这将确保正确的行为的时候,因为我只有T与比较?

What I am doing to circunvent the situation is using Object.Equals() method. Will it ensure the correct behavior all the time, since I am only comparing between T?

推荐答案

这是一个不受欢迎的限制约束系统。根据它的具体操作,除非它们在接口中定义你不能限制值类型。所以你不能限制对运营商的定义,因为它们不会对所有的值类型来定义,而结构约束允许任何类型的值在传递。

This is an unpopular limitation of the constraints system. You cannot constrain a value type according to specific operations on it unless they are defined in an interface. So you cannot constrain for operator definitions, as they will not be defined on all value types, and the struct constraint allows any value type to be passed in.

struct A { }

这是没有 == 中定义的,但你的约束说,你很乐意接受它。所以你不能用 ==

That has no == defined, and yet your constraint says you'd be happy to accept it. So you cannot use ==.

的原因及其对引用类型不同的是,因为总有一个定义 == 为他们提供(身份比较)。

The reason its different for reference types is because there is always a definition of == available for them (identity comparison).

的实施 == 枚举足够接近的实施等于你的解决办法是罚款。

The implementation of == on enum is close enough to the implementation of Equals that your workaround is fine.

的情况比较为> 与数字类型!没有这样的替代方法。该标准的数字有像 GREATERTHAN 方法等没有接口。

Compare with the situation for > with numeric types! No such workaround there. The standard numbers have no interface with methods like GreaterThan, etc.

这篇关于使用比较运算符,如'!='和'==',以约束在C#泛型的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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