运算符 == 不能应用于 C# 中的泛型类型吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/390900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't operator == be applied to generic types in C#?
提问by Hosam Aly
According to the documentation of the ==
operator in MSDN,
根据==
操作员在MSDN 中的文档,
For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings. User-defined value types can overload the == operator (see operator). So can user-defined reference types, although by default == behaves as described above for both predefined and user-defined reference types.
对于预定义的值类型,如果操作数的值相等,则相等运算符 (==) 返回 true,否则返回 false。对于字符串以外的引用类型,如果 == 的两个操作数引用同一个对象,则返回 true。对于字符串类型,== 比较字符串的值。用户定义的值类型可以重载 == 运算符(请参阅运算符)。用户定义的引用类型也可以,尽管 默认情况下 == 的行为与上述预定义和用户定义的引用类型相同。
So why does this code snippet fail to compile?
那么为什么这段代码无法编译呢?
bool Compare<T>(T x, T y) { return x == y; }
I get the error Operator '==' cannot be applied to operands of type 'T' and 'T'. I wonder why, since as far as I understand the ==
operator is predefined for all types?
我收到错误运算符 '==' 不能应用于类型 'T' 和 'T' 的操作数。我想知道为什么,因为据我所知,==
运算符是为所有类型预定义的?
Edit:Thanks, everybody. I didn't notice at first that the statement was about reference types only. I also thought that bit-by-bit comparison is provided for all value types, which I now know is notcorrect.
编辑:谢谢大家。起初我没有注意到该声明仅与引用类型有关。我还认为为所有值类型提供了逐位比较,我现在知道这是不正确的。
But, in case I'm using a reference type, would the ==
operator use the predefined reference comparison, or would it use the overloaded version of the operator if a type defined one?
但是,如果我使用的是引用类型,那么==
运算符会使用预定义的引用比较,还是会使用运算符的重载版本(如果类型定义了)?
Edit 2:Through trial and error, we learned that the ==
operator will use the predefined reference comparison when using an unrestricted generic type. Actually, the compiler will use the best method it can find for the restricted type argument, but will look no further. For example, the code below will always print true
, even when Test.test<B>(new B(), new B())
is called:
编辑 2:通过反复试验,我们了解到==
运算符在使用不受限制的泛型类型时将使用预定义的引用比较。实际上,编译器会使用它所能找到的最好的方法来处理受限类型参数,但不会再看下去了。例如,下面的代码将始终打印true
,即使Test.test<B>(new B(), new B())
被调用:
class A { public static bool operator==(A x, A y) { return true; } }
class B : A { public static bool operator==(B x, B y) { return false; } }
class Test { void test<T>(T a, T b) where T : A { Console.WriteLine(a == b); } }
采纳答案by Giovanni Galbo
"...by default == behaves as described above for both predefined and user-defined reference types."
“...默认情况下 == 的行为与上述预定义和用户定义的引用类型相同。”
Type T is not necessarily a reference type, so the compiler can't make that assumption.
类型 T 不一定是引用类型,因此编译器无法做出这种假设。
However, this will compile because it is more explicit:
但是,这将编译,因为它更明确:
bool Compare<T>(T x, T y) where T : class
{
return x == y;
}
Follow up to additional question, "But, in case I'm using a reference type, would the the == operator use the predefined reference comparison, or would it use the overloaded version of the operator if a type defined one?"
跟进附加问题,“但是,如果我使用引用类型,== 运算符会使用预定义的引用比较,还是会使用运算符的重载版本(如果定义了类型)?
I would have thought that == on the Generics would use the overloaded version, but the following test demonstrates otherwise. Interesting... I'd love to know why! If someone knows please share.
我原以为泛型上的 == 会使用重载的版本,但下面的测试表明情况并非如此。有趣...我很想知道为什么!如果有人知道请分享。
namespace TestProject
{
class Program
{
static void Main(string[] args)
{
Test a = new Test();
Test b = new Test();
Console.WriteLine("Inline:");
bool x = a == b;
Console.WriteLine("Generic:");
Compare<Test>(a, b);
}
static bool Compare<T>(T x, T y) where T : class
{
return x == y;
}
}
class Test
{
public static bool operator ==(Test a, Test b)
{
Console.WriteLine("Overloaded == called");
return a.Equals(b);
}
public static bool operator !=(Test a, Test b)
{
Console.WriteLine("Overloaded != called");
return a.Equals(b);
}
}
}
Output
输出
Inline: Overloaded == called
内联:重载 == 调用
Generic:
通用的:
Press any key to continue . . .
按任意键继续 。. .
Follow Up 2
跟进 2
I do want to point out that changing my compare method to
我确实想指出将我的比较方法更改为
static bool Compare<T>(T x, T y) where T : Test
{
return x == y;
}
causes the overloaded == operator to be called. I guess without specifying the type (as a where), the compiler can't infer that it should use the overloaded operator... though I'd think that it would have enough information to make that decision even without specifying the type.
导致调用重载的 == 运算符。我想如果没有指定类型(作为where),编译器无法推断它应该使用重载运算符......尽管我认为即使没有指定类型,它也会有足够的信息来做出决定。
回答by Johannes Schaub - litb
The compile can't know T couldn't be a struct (value type). So you have to tell it it can only be of reference type i think:
编译不能知道 T 不能是结构(值类型)。所以你必须告诉它它只能是我认为的引用类型:
bool Compare<T>(T x, T y) where T : class { return x == y; }
It's because if T could be a value type, there could be cases where x == y
would be ill formed - in cases when a type doesn't have an operator == defined. The same will happen for this which is more obvious:
这是因为如果 T 可以是值类型,则可能存在格式错误的情况x == y
- 在类型没有定义运算符 == 的情况下。同样的事情也会发生,这更明显:
void CallFoo<T>(T x) { x.foo(); }
That fails too, because you could pass a type T that wouldn't have a function foo. C# forces you to make sure all possible types always have a function foo. That's done by the where clause.
这也失败了,因为您可以传递一个没有函数 foo 的类型 T。C# 强制您确保所有可能的类型始终具有函数 foo。这是由 where 子句完成的。
回答by shahkalpesh
bool Compare(T x, T y) where T : class { return x == y; }
The above will work because == is taken care of in case of user-defined reference types.
In case of value types, == can be overridden. In which case, "!=" should also be defined.
以上将起作用,因为在用户定义的引用类型的情况下会处理 == 。
在值类型的情况下, == 可以被覆盖。在这种情况下,还应定义“!=”。
I think that could be the reason, it disallows generic comparison using "==".
我认为这可能是原因,它不允许使用“==”进行通用比较。
回答by Jon Limjap
It appears that without the class constraint:
似乎没有类约束:
bool Compare<T> (T x, T y) where T: class
{
return x == y;
}
One should realize that while class
constrained Equals
in the ==
operator inherits from Object.Equals
, while that of a struct overrides ValueType.Equals
.
人们应该意识到,whileclass
约束Equals
在==
运算符中继承自Object.Equals
,而结构体则覆盖了ValueType.Equals
。
Note that:
注意:
bool Compare<T> (T x, T y) where T: struct
{
return x == y;
}
also gives out the same compiler error.
也给出了相同的编译器错误。
As yet I do not understand why having a value type equality operator comparison is rejected by the compiler. I do know for a fact though, that this works:
到目前为止,我不明白为什么编译器拒绝了值类型相等运算符比较。不过,我确实知道,这是有效的:
bool Compare<T> (T x, T y)
{
return x.Equals(y);
}
回答by Jon Skeet
As others have said, it will only work when T is constrained to be a reference type. Without any constraints, you can compare with null, but only null - and that comparison will always be false for non-nullable value types.
正如其他人所说,它仅在 T 被约束为引用类型时才有效。没有任何约束,您可以与 null 进行比较,但只能与 null 进行比较 - 对于不可为 null 的值类型,该比较将始终为 false。
Instead of calling Equals, it's better to use an IComparer<T>
- and if you have no more information, EqualityComparer<T>.Default
is a good choice:
与其调用 Equals,不如使用IComparer<T>
- 如果您没有更多信息,这EqualityComparer<T>.Default
是一个不错的选择:
public bool Compare<T>(T x, T y)
{
return EqualityComparer<T>.Default.Equals(x, y);
}
Aside from anything else, this avoids boxing/casting.
除此之外,这避免了拳击/铸造。
回答by Marc Gravell
In general, EqualityComparer<T>.Default.Equals
should do the job with anything that implements IEquatable<T>
, or that has a sensible Equals
implementation.
一般来说,EqualityComparer<T>.Default.Equals
应该用任何实现IEquatable<T>
或具有合理Equals
实现的东西来完成这项工作。
If, however, ==
and Equals
are implemented differently for some reason, then my work on generic operatorsshould be useful; it supports the operatorversions of (among others):
但是,如果由于某种原因==
而Equals
以不同的方式实现,那么我在泛型运算符方面的工作应该是有用的;它支持(除其他外)运营商版本:
- Equal(T value1, T value2)
- NotEqual(T value1, T value2)
- GreaterThan(T value1, T value2)
- LessThan(T value1, T value2)
- GreaterThanOrEqual(T value1, T value2)
- LessThanOrEqual(T value1, T value2)
- 等于(T值1,T值2)
- NotEqual(T value1, T value2)
- 大于(T值1,T值2)
- 小于(T值1,T值2)
- GreaterThanOrEqual(T value1, T value2)
- 小于或等于(T 值 1,T 值 2)
回答by Recep
There is an MSDN Connect entry for this here
没有此的MSDN连接进入这里
Alex Turner's reply starts with:
亚历克斯·特纳 (Alex Turner) 的回复开头是:
Unfortunately, this behavior is by design and there is not an easy solution to enable use of == with type parameters that may contain value types.
不幸的是,这种行为是设计使然,并没有一个简单的解决方案来启用 == 与可能包含值类型的类型参数。
回答by Ben Voigt
So many answers, and not a single one explains the WHY? (which Giovanni explicitly asked)...
这么多答案,没有一个能解释为什么?(乔瓦尼明确要求)...
.NET generics do not act like C++ templates. In C++ templates, overload resolution occurs after the actual template parameters are known.
.NET 泛型的行为不像 C++ 模板。在 C++ 模板中,重载解析发生在知道实际模板参数之后。
In .NET generics (including C#), overload resolution occurs without knowing the actual generic parameters. The only information the compiler can use to choose the function to call comes from type constraints on the generic parameters.
在 .NET 泛型(包括 C#)中,重载解析发生时不知道实际的泛型参数。编译器可以用来选择要调用的函数的唯一信息来自泛型参数的类型约束。
回答by Christophe
If you want to make sure the operators of your custom type are called you can do so via reflection. Just get the type using your generic parameter and retrieve the MethodInfo for the desired operator (e.g. op_Equality, op_Inequality, op_LessThan...).
如果您想确保调用自定义类型的运算符,您可以通过反射来实现。只需使用泛型参数获取类型并检索所需运算符的 MethodInfo(例如 op_Equality、op_Inequality、op_LessThan...)。
var methodInfo = typeof (T).GetMethod("op_Equality",
BindingFlags.Static | BindingFlags.Public);
Then execute the operator using the MethodInfo's Invoke method and pass in the objects as the parameters.
然后使用 MethodInfo 的 Invoke 方法执行操作符,并将对象作为参数传入。
var result = (bool) methodInfo.Invoke(null, new object[] { object1, object2});
This will invoke your overloaded operator and not the one defined by the constraints applied on the generic parameter. Might not be practical, but could come in handy for unit testing your operators when using a generic base class that contains a couple of tests.
这将调用您的重载运算符,而不是由应用于泛型参数的约束定义的运算符。可能不实用,但在使用包含几个测试的通用基类时可以方便地对您的运算符进行单元测试。
回答by Charlie
I wrote the following function looking at the latest msdn. It can easily compare two objects x
and y
:
我编写了以下函数,查看最新的 msdn。它可以轻松地比较两个对象x
和y
:
static bool IsLessThan(T x, T y)
{
return ((IComparable)(x)).CompareTo(y) <= 0;
}