IndexOutOfRangeException在索引的getter索引、IndexOutOfRangeException、getter

2023-09-05 00:43:49 作者:风软一江水✿

在我的索引属性我检查索引是否出界与否。如果是,我抛出一个 IndexOutOfBoundsException异常

In my indexed property I check whether the index is out of bounds or not. If it is, I throw an IndexOutOfBoundsException.

当我运行code分析员(在VS12),它与CA1065抱怨:在意外的位置意外异常

When I run the Code Analyst (in VS12) it complains with CA1065: Unexpected exception in unexpected location.

参照CA1065的说明中,只

Referring to the description of CA1065, only

System.InvalidOperationException
System.NotSupportedException
System.ArgumentException
KeyNotFoundException

被允许在索引的getter。

are allowed in an indexed getter.

投掷 IndexOutOfBoundsException异常很自然地我,所以有什么理由吗? (是的,我知道我可以把报警的时候,我只是想知道的推理)

Throwing IndexOutOfBoundsException seems natural to me, so what is the reasoning here? (And yes, I know I can turn the warning off, I just want to know the reasoning)

推荐答案

很多类使用 ArgumentOutOfRangeException 此,其中包括的 名单,其中,T> 。这是的ArgumentException 子类,所以应该满足的规则。我猜你可能会说,直接访问的载体等,但实际上不是一个方法调用(它是一个专用的运算code - ldelem * ),所以该指数在这种情况下,是不是的实际上的一个参数。似乎是一个薄弱的论据,虽然。

A lot of classes use ArgumentOutOfRangeException for this, including List<T>. This is a subclass of ArgumentException so should satisfy the rule. I guess you could argue that for a vector etc accessed directly, there isn't actually a method call (it is a dedicated opcode - ldelem*), so the index in that case isn't actually an argument. Seems a weak argument, though.