用负数组大小引发OverflowException背后的理由吗? [英] Rationale behind OverflowException thrown with negative array size?

查看:84
本文介绍了用负数组大小引发OverflowException背后的理由吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写可简化为以下内容的代码后:

After writing code that can be boiled down to the following:

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

我很惊讶它抛出一个 OverflowException . OverflowException 状态的文档:

I was surprised that it threw an OverflowException. The docs for OverflowException state:

在进行算术,转换或转换操作时引发的异常在检查的上下文中会导致溢出.

我看不到为该异常提供负大小和数组长度如何适合此异常的描述,因此深入研究并发现这确实是指定的行为:

I couldn't see how providing a negative size for and array length fits into the description given for this exception, so delved a little deeper and found that this is indeed the specified behaviour:

将尺寸长度的计算值验证为如下.如果一个或多个值小于零,则抛出System.OverflowException,并且不再执行任何步骤.

我想知道为什么选择了OverflowException.如果你问我,这是很误导的.这花费了我至少5分钟的调查时间(此处未计算出我的想法).任何人都可以对这个(根据我的想法)特殊的设计决策有所了解吗?

I wonder why OverflowException was chosen. It's pretty misleading if you ask me. It cost me at least 5 minutes of investigation (not counting my musings here). Can anyone shed any light on this (to my thinking) peculiar design decision?

推荐答案

几乎可以肯定这是一种优化. .NET框架代码对于检查参数以使程序员落入成功之门非常虔诚.但这不是免费的.成本是微不足道的,许多类方法比检查花费的机器周期更多.

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.

但是数组很特殊.它们是框架中非常核心的数据结构.几乎每个集合类都建立在它们之上. Array类中的任何开销都会直接影响位于其上的许多代码的效率.避免检查是可以的,当内部代码需要将该值强制转换为unsigned时,无论如何都会对其进行隐式检查.而且它跳闸非常罕见.因此,对其进行两次检查并不值得获得更好的异常消息.

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.

这篇关于用负数组大小引发OverflowException背后的理由吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆