2009-10-19 3 views
0

Dans la documentation pour la fonction Comparer en classe il dit Comparer:Comparer.Compare a besoin d'un objet qui implémente IComparable mais jetteront exception sinon le premier paramètre est

If a implements IComparable, then a. CompareTo (b) is returned; otherwise, if b implements IComparable, then the negated result of b. CompareTo (a) is returned.

Mais quand je le tester comme il Il coutures demandera que la première entrée implémente Icomparable. Le code suivant produira l'erreur:

class Program 
{ 
    static void Main(string[] args) 
    { 
     Test t1 = new Test(); 
     Test2 t2 = new Test2(); 

     int i = Comparer.Default.Compare(t1,t2); 

    } 
} 

class Test 
{ 
} 

class Test2 : IComparable 
{ 
    public int CompareTo(object obj) 
    { 
     return 0; 
    } 
} 

Est-ce juste moi ou les documents sont-ils faux?

Répondre

2

Refecteur dit qu'il vérifie seulement si un IComparable implémente.

public int Compare(object a, object b) 
{ 
if (a == b) 
{ 
    return 0; 
} 
if (a == null) 
{ 
    return -1; 
} 
if (b == null) 
{ 
    return 1; 
} 
if (this.m_compareInfo != null) 
{ 
    string str = a as string; 
    string str2 = b as string; 
    if ((str != null) && (str2 != null)) 
    { 
     return this.m_compareInfo.Compare(str, str2); 
    } 
} 
IComparable comparable = a as IComparable; 
if (comparable == null) 
{ 
    throw new ArgumentException(Environment.GetResourceString("Argument_ImplementIComparable")); 
} 
return comparable.CompareTo(b); 

}

+1

Je ne suis pas sûr que vous pouvez juste après décompilé source proprietry ici. – Joren

Questions connexes