Array-Quellcode ist in reference source verfügbar und kann mit ILSpy de-kompiliert werden.
In Referenzquelle, finden Sie in Zeile 2753 dann 2809:
// -----------------------------------------------------------
// ------- Implement ICollection<T> interface methods --------
// -----------------------------------------------------------
...
[SecuritySafeCritical]
bool Contains<T>(T value) {
//! Warning: "this" is an array, not an SZArrayHelper. See comments above
//! or you may introduce a security hole!
T[] _this = JitHelpers.UnsafeCast<T[]>(this);
return Array.IndexOf(_this, value) != -1;
}
Und IndexOf
endet auf dieser IndexOf
oben, die eine O (n) Algorithmus ist.
internal virtual int IndexOf(T[] array, T value, int startIndex, int count)
{
int endIndex = startIndex + count;
for (int i = startIndex; i < endIndex; i++) {
if (Equals(array[i], value)) return i;
}
return -1;
}
Diese Methoden sind auf einer speziellen Klasse SZArrayHelper in derselben Quelldatei, und wie in Zeile 2721 erläutert, ist dies die Umsetzung Ihrer für suchen.
// This class is needed to allow an SZ array of type T[] to expose IList<T>,
// IList<T.BaseType>, etc., etc. all the way up to IList<Object>. When the following call is
// made:
//
// ((IList<T>) (new U[n])).SomeIListMethod()
//
// the interface stub dispatcher treats this as a special case, loads up SZArrayHelper,
// finds the corresponding generic method (matched simply by method name), instantiates
// it for type <T> and executes it.
Über O (1) Komplexität zu erreichen, können Sie es zu einem HashSet umwandeln sollte:
var lookupHashSet = new HashSet<T>(yourArray);
...
var hasValue = lookupHashSet.Contains(testValue);
Natürlich ist diese Umwandlung ist ein O (n) -Operation. Wenn Sie nicht viele Nachschlagewerke zu tun haben, ist es strittig.
Hinweis from documentation auf diesem Konstruktor:
Wenn Sammlung Duplikate enthält, wird die Menge eines jeden einzelnen Element enthalten. Es wird keine Ausnahme ausgelöst. Daher ist die Größe der resultierenden Menge nicht identisch mit der Größe der Sammlung.
FWIW, 'Contains' ist auf' ICollection ', nicht' IList '. –
@JamesThorpe wirklich? https://msdn.microsoft.com/de-de/library/bb336401(v=vs.110).aspx –
[Ja] (http://referencesource.microsoft.com/#mscorlib/system/collections/generic/ icollection.cs, 34). 'IList' erbt von 'ICollection '. –