简体   繁体   English

C#:为什么范围的上限是互斥的?

[英]C#: Why is the upper bound of ranges exclusive?

C# 8 added the ranges syntax to C#: C# 8 向 C# 添加了范围语法:

var slice = myArray[0..2];

What I find not so intuitive is that the upper bound ( 2 in the previous example) is exclusive - not inclusive ;我发现不太直观的是上限(上一个示例中的2 )是排他性的- 不包括在内 ie myArray[0..2] returns a slice with 2 elements (0 and 1), not with 3 elements.myArray[0..2]返回一个包含 2 个元素(0 和 1)而不是 3 个元素的切片。

So my question is: Why did the C# language designers choose to make the upper bound exclusive?所以我的问题是:为什么C#语言设计者选择让上限独占?

Both the ranges documentation as well as the design champion issue simply state that the upper bound is exclusive - without giving any explanation as to why (at least none that I could find). 范围文档设计冠军问题都简单地说明上限是排他性的 - 没有给出任何解释原因(至少我找不到)。 There also was a discussion about this on GitHub but it also doesn't seem to contain any official explanation.在 GitHub 上也有一个关于这个的讨论,但它似乎也没有包含任何官方解释。

By searching StackOverflow I stumbled across the same question for Python .通过搜索 StackOverflow,我偶然发现了 Python相同问题 Python also treats the upper bound as exclusive. Python 也将上限视为排他的。 So I can imagine that the C# language designers were looking at other languages (that have ranges) and were trying to make C#'s behavior consistent with other languages.所以我可以想象 C# 语言设计者正在研究其他语言(有范围)并试图使 C# 的行为与其他语言保持一致。 But I'm still wondering if there is any official documentation on this decision.但我仍然想知道是否有关于这个决定的任何官方文件。

There are a lot of design decisions that just won't have satisfying answers.有很多设计决策不会有令人满意的答案。 However, this one at least has a paper-trail you can follow in the design notes (in one or more mentions) starting at the following link.但是,这个至少有一个纸迹,您可以从以下链接开始的设计说明(在一个或多个提及中)中遵循。

Note : This was just an arbitrary decision, the reason they chose exclusive is because they chose exclusive.注意:这只是一个武断的决定,他们之所以选择排他是因为他们选择了排他。 It could easily not have been the case due to the pros and cons.由于利弊,情况很可能并非如此。

C# Language Design Notes for Jan 22, 2018 2018 年 1 月 22 日的 C# 语言设计说明

... ...

Conclusion结论

Let us go with .. means exclusive. Let us go with ..意味着独家。 Since we've chosen to focus on the indexing/slicing scenario, this seems the right thing to do:由于我们选择专注于索引/切片场景,这似乎是正确的做法:

  • It allows a.Length as an endpoint without adding/subtracting 1.它允许a.Length作为端点,而无需加/减 1。
  • It lets the end of one range be the beginning of the next without overlap它让一个范围的结束成为下一个不重叠的开始
  • It avoids ugly empty ranges of the form x..x-1它避免了x..x-1形式的丑陋空范围

And as @vc74 mentions in the comments and also stated in the document supplied, other languages like Python follow this convention, however others don't.正如@vc74在评论中提到的以及在提供的文档中所述,其他语言(如 Python)遵循此约定,但其他语言则没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM