在开始和结束算法方面,我们决定遵循Python. 0
表示第一个元素(一如既往),^0
表示长度"元素,即最后一个元素.这样,您将获得一个简单的关系,其中元素从开始的位置加上其从结束的位置等于长度. ^x
中的x
是您自己进行数学运算后要减去的长度.
We decided to follow Python when it comes to the from-beginning and from-end arithmetic. 0
designates the first element (as always), and ^0
the "length’th" element, i.e. the one right off the end. That way you get a simple relationship, where an element's position from beginning plus its position from end equals the length. the x
in ^x
is what you would have subtracted from the length if you’d done the math yourself.
为什么不使用减号(-
)而不是新帽子(^
)运算符?这主要与范围有关.再次与Python和大多数行业保持一致,我们希望我们的范围在开始时就包含所有内容,而在结尾处包含所有内容.您传递的要说范围应该一直到终点的索引是什么?在C#中答案很简单:x..^0
从x
到末尾.在Python中,没有可以提供的显式索引:-0
不起作用,因为它等于第一个元素0
!因此,在Python中,您必须完全不使用end索引来表示到达末尾的范围:x..
.如果计算了范围的末尾,那么您需要记住要有特殊的逻辑,以防出现在0
上.与x..-y
一样,在其中计算y
并得出0
.这是常见的滋扰和错误来源.
Why not use the minus (-
) instead of the new hat (^
) operator? This primarily has to do with ranges. Again in keeping with Python and most of the industry, we want our ranges to be inclusive at the beginning, exclusive at the end. What is the index you pass to say that a range should go all the way to the end? In C# the answer is simple: x..^0
goes from x
to the end. In Python, there is no explicit index you can give: -0
doesn’t work, because it is equal to 0
, the first element! So in Python, you have to leave the end index off completely to express a range that goes to the end: x..
. If the end of the range is computed, then you need to remember to have special logic in case it comes out to 0
. As in x..-y
, where y
was computed and came out to 0
. This is a common nuisance and source of bugs.
最后,请注意,索引和范围是.NET/C#中的第一类类型.它们的行为不依赖于它们的应用,甚至不用于索引器.您可以完全定义自己的使用Index的索引器和使用Range
的索引器-我们将在其中添加此类索引器. Span
.但是,例如,您也可以使用采用范围的方法.
Finally, note that indices and ranges are first class types in .NET/C#. Their behavior is not tied to what they are applied to, or even to be used in an indexer. You can totally define your own indexer that takes Index and another one that takes Range
– and we’re going to add such indexers to e.g. Span
. But you can also have methods that take ranges, for instance.
我的答案
我认为这与我们习惯的经典语法相符:
My answer
I think this is to match the classic syntax we are used to:
value[^1] == value[value.Length - 1]
如果使用0,则两种语法并排使用时会造成混淆.这样,它的认知负荷就会更低.
If it used 0, it would be confusing when the two syntaxes were used side-by-side. This way it has lower cognitive load.
Python等其他语言也使用相同的约定.
Other languages like Python also use the same convention.
这篇关于为什么C#8数组切片功能中新的hat-operator索引不从0开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!