Home >Backend Development >C++ >When Does C#'s == Operator Fail and How Can You Handle It?
C#
The computing symbol is used to compare the equal nature of the two objects, which is very convenient. Although operational symbols are commonly used in all types, it cannot be used in some cases.
==
A example is a relatively unconstrained generic type. The code fragment provided in the problem cannot be compiled because it tries to compare the generic parameters of the two types T. If there is no constraint on T, this type may be a value type. In this case, the ==
operator cannot be directly applied.
For example, and bool Compare<T>(T x, T y) { return x == y; }
equivalent types do not have a predetermined ==
operator. They use the
operator for checking object references. int
float
Therefore, if the constraint on T is not specified, the compiler cannot determine whether it is used as a ==
operator with a predetermined type of reference type, or the Equals
method with value type. To solve this problem, the T is constrained into a reference type. string
==
Now, assuming you will reference the type as the type parameter. In this case, the operator will compare the predefined reference, not any heavy load version of the operator. This is because predefined references are considered more basic and reliable.
If you insufficient information about type parameters, you can use the ==
interface or Equals
static method. These methods provide a standardized comparison method, regardless of its type.
The above is the detailed content of When Does C#'s == Operator Fail and How Can You Handle It?. For more information, please follow other related articles on the PHP Chinese website!