📜  C#8.0中的范围结构

📅  最后修改于: 2021-05-29 14:44:45             🧑  作者: Mango

C#8.0引入了一种新的预定义结构,称为Range结构。此结构用于表示具有开始索引和结束索引的范围。它提供了一种使用..运算符创建范围的新样式。该运算符用于创建具有开始和结束索引的范围。同样,在Range结构的帮助下,您还可以创建范围类型的变量。

// C# program to illustrate how to create ranges
using System;
  
namespace range_example {
  
class GFG {
  
    // Main Method
    static void Main(string[] args)
    {
        int[] marks = new int[] {23, 45, 67, 88, 99,
                            56, 27, 67, 89, 90, 39};
  
        // Creating variables of range type
        // And initalize the range 
        // varibales with a range
        // Using .. operator
        Range r1 = 1..5;
        Range r2 = 6..8;
  
        var a1 = marks[r1];
        Console.Write("Marks List 1: ");
        foreach(var st_1 in a1)
            Console.Write($" {st_1} ");
  
        var a2 = marks[r2];
        Console.Write("\nMarks List 2: ");
        foreach(var st_2 in a2)
            Console.Write($" {st_2} ");
  
        // Creating a range
        // Using .. operator
        var a3 = marks[2..4];
        Console.Write("\nMarks List 3: ");
        foreach(var st_3 in a3)
            Console.Write($" {st_3} ");
  
        var a4 = marks[4..7];
        Console.Write("\nMarks List 4: ");
        foreach(var st_4 in a4)
            Console.Write($" {st_4} ");
    }
}
}

输出:

Marks List 1:  45  67  88  99 
Marks List 2:  27  67 
Marks List 3:  67  88 
Marks List 4:  99  56  27

建设者

Constructor Description
Range(Index, Index) This constructor is used to create a new Range instance with the specified starting and ending indexes.

特性

Property Description
All This property is used to get a Range object that starts from the first element to the end.
End This property is used to get an Index that represents the exclusive end index of the range.
Start This property is used to get the inclusive start index of the Range.

方法

Method Description
EndAt(Index) This method is used to create a Range object starting from the first element in the collection to a specified end index.
Equals() This method is used to check whether the current range is equal to a specified range.
GetHashCode() This method is used to find the hash code for this instance.
GetOffsetAndLength(Int32) This method is used to calculate the start offset and length of the given range object with the help of a collection length.
StartAt(Index) This method is used to create a new Range instance starting from a specified start index to the end of the collection.
ToString() This method returns the string representation of the current Range object.