gpt4 book ai didi

c# - 具有两个索引参数的方法,其中有效范围相互依赖 : ArgumentOutOfRangeException OR ArgumentException?

转载 作者:太空宇宙 更新时间:2023-11-03 22:54:21 27 4
gpt4 key购买 nike

考虑以下场景:

一个方法期望两个索引被确定为参数,并且其中一个等于或大于另一个,使有效范围相互依赖。

例如,获取数组子副本的方法,具有开始和结束索引:

public static T[] Sub<T>(this T[] @this, int start, int end) {
//Somewhere within...
var newLength = end - start;
if (newLength < 0)
//Throw exception because end<start...
}

现在,这是(诚然有点无关紧要,但仍然很有趣 [恕我直言])的问题:

ArgumentOutOfRangeException 定义为:

The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.

哪种适合这种情况,哪种不适合:

  • 该方法定义了“索引 A 必须小于索引 B”,但是定义了 A 之间的关系B;不完全是 AB 的有效范围...
  • 最终,在这个例子中,B的有效范围由A定义;不是(明确地)通过方法。

另一方面,ArgumentException 定义为:

The exception that is thrown when one of the arguments provided to a method is not valid.

考虑到我关于 B 的有效范围如何由 A 定义的论点,这实际上非常适合:

  • 一个参数 B 在小于 A无效

然而,异常(不管是哪个)仍然基于一个索引,并且直接绑定(bind)到有效或无效的范围如果索引...

所以...

是否应该抛出更一般的 ArgumentException,因为它是使它们无效的索引的组合?

是否应该抛出更具体的 ArgumentOutOfRangeException,即使此处的“无效”不(?)完全符合预期用途异常的?

还是应该抛出 SomethingElseEntirelyException

最佳答案

我会选择 ArgumentOutOfRangeException .这与框架中其他地方的其他示例相吻合:

另一方面,我也应该举一个反例:

我不确定为什么最后一个是这样定义的,但我认为该方法根据其他参数和状态定义有效值范围是合理的物体。不过,我个人会尝试根据较早 参数来定义特定参数的有效值范围 - 所以如果您有 Foo(int x, int y)要求 x < y ,那么我会说 y的有效范围是根据 x 定义的.

关于c# - 具有两个索引参数的方法,其中有效范围相互依赖 : ArgumentOutOfRangeException OR ArgumentException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46138032/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com