C#8.0引入了一种新的预定义结构,称为索引结构。此结构用于表示可以用作从开始或结束开始的集合或序列的索引的类型。它提供了一种新的索引样式来访问元素,即^运算符。该运算符用于查找指定集合或序列的最后一个元素。同样在Index struct的帮助下,您可以创建索引类型的变量。
例子:
// C# program to illustrate
// the concept of index
using System;
namespace example {
class GFG {
// Main Method
static void Main(string[] args)
{
// Creating and initializing an array
int[] num = new int[] {1, 2, 3, 4, 5, 6, 7};
// Accessing the starting
// elements of the array
Console.WriteLine("Starting Elements");
Console.WriteLine(num[1]);
Console.WriteLine(num[2]);
Console.WriteLine(num[3]);
// Accessing the last
// elements of the array
Console.WriteLine("Last Elements");
Console.WriteLine(num[^2]);
Console.WriteLine(num[^3]);
Console.WriteLine(num[^4]);
Console.WriteLine();
// Index as a variable
Index i = ^1;
Console.WriteLine("Index as a variable: " + num[i]);
}
}
}
输出:
Starting Elements
2
3
4
Last Elements
6
5
4
Index as a variable: 7
建设者
Constructor | Description |
---|---|
Index(Int32, Boolean) | It is used to initialize a new Index with a specified index position and a value that indicates if the index is from the start or the end of a collection. |
特性
Property | Description |
---|---|
End | It is used to get an Index that points beyond the last element. |
IsFromEnd | It is used to get a value that indicates whether the index is from the start or the end. |
Start | It is used to get an Index that points to the first element of a collection. |
Value | It is used to get the index value. |
方法
Method | Description |
---|---|
Equals() | It is used to check whether the given index is equal to another index or not. |
FromEnd(Int32) | It is used to create an Index from the end of a collection at a specified index position. |
FromStart(Int32) | It is used to create an Index from the specified index at the start of a collection. |
GetHashCode() | It return the hash code for the given instance. |
GetOffset(Int32) | It is used to calculate the offset from the start of the collection using the given collection length. |
ToString() | It is used to return the string representation of the current Index instance. |