Frage

Nach dem Schreiben von Code, der folgend eingekocht werden kann:

var size=-1;
var arr=new byte[size];

Ich war überrascht, dass es warf ein Overflow. Die Dokumentation für Overflowzustand:

Die Ausnahme, die ausgelöst wird, wenn eine arithmetische, Gießen oder Umwandlungsoperation in einem geprüften Kontext zu einem Überlauf.

Ich konnte nicht sehen, wie eine negative Größe für und Array-Länge paßt in die Beschreibung für diese Ausnahme gegeben Bereitstellung, so ein wenig tiefer vertiefte und fand, dass dies tatsächlich das angegebene Verhalten:

die berechneten Werte für die Dimensionslängen werden validiert folgt. Wenn eine oder mehrere der Werte weniger sind als Null ist, ein System.OverflowException geworfen wird und keine weiteren Schritte ausgeführt.

Ich frage mich, warum Overflow gewählt wurde. Es ist irreführend, hübsch, wenn Sie mich fragen. Es kostete mich mindestens 5 Minuten der Untersuchung (nicht meine Gedanken hier zu zählen). Kann jemand Aufschluss über diese (zu meinem Denken) eigentümliche Design-Entscheidung?

War es hilfreich?

Lösung

This is almost certainly an optimization. The .NET framework code is pretty religious about checking arguments to let the programmer fall in the pit of success. But that doesn't come for free. The cost is fairly minuscule, many class methods take lots more machine cycles than is spent on the checking.

But arrays are special. They are the very core data structure in the framework. Almost every collection class is built on top of them. Any overhead put in the Array class directly impacts the efficiency of a lot of code that sits on top of it. Avoiding the check is okay, it gets implicitly checked anyway when the internal code needs to cast the value to unsigned. And it is very rare that it trips. So checking it twice is not quite worth the better exception message.

Andere Tipps

OverflowException, in the documentation, basically defines an overflow as something that:

produces a result that is outside the range of the data type

In this case, negative values are outside of the valid range for an array size (or really, any size).

I could see the argument that ArgumentOutOfRangeException might be, in some ways, better - however, there is no argument involved in an array definition (as its not a method), so it, too, would not be a perfect choice.

It might be because that size is an unsigned int. It stores -1 in two's complement, which when looked at as a unsigned int, is the maximum positive integer that can be stored. If this number is bigger than the possible size of an array, it will overflow.

Warning: this is pure speculation.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top