ByTwos
and
ByTwos
would be invalid.
Comparing Instances of a Type Parameter
Sometimes you will want to compare two instances of a type parameter. For example, you
might want to write a generic method called
IsIn( )
that returns true if some value is
contained within an array. To accomplish this, you might first try something like this:
// This won’t work!
public static bool IsIn(T what, T[] obs) {
foreach(T v in obs)
if(v == what) // Error!
return true;
return false;
}
Unfortunately, this attempt won’t work. Because
T
is a generic type, the compiler has no
way to know precisely how two objects should be compared for equality. Should a bitwise
comparison be done? Should only certain fields be compared? Should reference equality be
used? The compiler has no way to answer these questions.
To enable two objects of a generic type parameter to be compared, you must use the
CompareTo( )
method defined by one of .NET’s standard interfaces:
IComparable
. This
interface is implemented by all of C#’s built-in types, including
Do'stlaringiz bilan baham: |