📜  如何在C#中创建到指定端点的范围?

📅  最后修改于: 2021-05-29 19:03:58             🧑  作者: Mango

范围结构在C#8.0中引入。它表示具有开始索引和结束索引的范围。借助Range结构提供的EndAt()方法,允许您从指定集合或序列的第一个元素到指定的结束索引的Range对象。换句话说,EndAt()方法返回一个范围,该范围从给定集合的第一个元素开始,一直到指定的索引。

句法:

public static Range EndAt(Index end);

在此,索引结束表示结束索引。

范例1:

// C# program to illustrate how
// to create a range using
// EndAt() method of Range struct
using System;
  
namespace range_example {
  
class GFG {
  
    // Main Method 
    static void Main(string[] args)
    {
        // Creating range
        // using Range constructor
        var r1 = new Range(2, 4);
  
        // Creating range
        // using Range operator
        Range r2 = 1..10;
  
        // Creating a range
        // using EndAt() method
        var r3 = Range.EndAt(6);
  
        // Displaying all the ranges
        Console.WriteLine("Range_1: " + r1);
        Console.WriteLine("Range_2: " + r2);
        Console.WriteLine("Range_3: " + r3);
    }
}
}

输出:

Range_1: 2..4
Range_2: 1..10
Range_3: 0..6

范例2:

// C# program to illustrate
// how to create a range using
// EndAt() method of Range struct
using System;
  
namespace range_example {
  
class GFG {
  
    // Main Method
    static void Main(string[] args)
    {
        // Creating and initializing an array
        int[] arr = new int[8] {100, 200, 300, 
                     400, 500, 600, 700, 800};
  
        // Creating a range
        // using EndAt() method
        var r = Range.EndAt(5);
        var new_arr = arr[r];
  
        // Displaying the range
        // and the elements
        Console.WriteLine("Range: " + r);
        Console.Write("Numbers: ");
  
        foreach(var i in new_arr)
            Console.Write($" [{i}]");
    }
}
}

输出:

Range: 0..5
Numbers:  [100] [200] [300] [400] [500]