C# Type De Comparaison: Type.Est égale à vs opérateur ==
Resharper suggère que la suite être modifié à partir de:
Type foo = typeof( Foo );
Type bar = typeof( Bar );
if( foo.Equals( bar ) ) { ... }
À:
if( foo == bar ) { ... }
opérateur ==
//Summary:
// Indicates whether two System.Type objects are equal.
//
//Parameters:
// left:
// The first object to compare.
//
// right:
// The second object to compare.
//
//Returns:
// true if left is equal to right; otherwise, false.
public static bool operator ==( Type left, Type right );
Equals( Type o )
//Summary:
// Determines if the underlying system type of the current System.Type is the
// same as the underlying system type of the specified System.Type.
//
//Parameters:
// o:
// The System.Type whose underlying system type is to be compared with the underlying
// system type of the current System.Type.
//
//Returns:
// true if the underlying system type of o is the same as the underlying system
// type of the current System.Type; otherwise, false.
public virtual bool Equals( Type o );
Question
Pourquoi operator ==
être recommandée au cours de Equals( Type o )
lorsque l'on compare les Types?
Vous devez vous connecter pour publier un commentaire.
Je vous suggère de lire l'excellent quand on est un type de pas type? blog de Brad Wilson. Pour résumer: un runtime type (représenté par le type interne RuntimeType), géré par le CLR n'est pas toujours la même comme un
Type
, qui peut être prolongée.Equals
permettra de vérifier la système sous-jacent de type, alors que==
va vérifier le type lui-même.Un exemple simple:
La raison en est simple: Les deux sont fonctionnellement équivalents, dans ce cas, et le dernier est plus lisible.
De http://blogs.msdn.com/b/csharpfaq/archive/2004/03/29/when-should-i-use-and-when-should-i-use-equals.aspx