C#8.0中Index Struct的Index(Int32,Boolean)构造函数用于初始化具有指定索引位置和值的新索引,该值显示索引是从集合或序列的开头还是结尾开始。如果指定的索引从头开始创建,则索引值1将指向最后一个元素,索引值0将指向最后一个元素之外。
句法:
public Index (int Value, bool FromEnd = false);
在这里,Value是索引值,并且是System.Int32类型。索引的值应等于或大于零。 FromEnd是一个布尔值,它指示索引是从集合或序列的开头还是结尾开始。在C#8.0或更高版本上执行的以下代码:
范例1:
// C# program to illustrate
// the use of Index constructor
using System;
namespace example {
class GFG {
static void Main(string[] args)
{
// Creating and initializing an array
string[] greetings = new string[] {"Hello", "Hola", "Namaste",
"Bonjour", "Ohayo", "Ahnyounghaseyo"};
// Creating new indexes
// Using Index() constructor
var val1 = new Index(1, true);
var val2 = new Index(2, true);
var val3 = new Index(3, true);
var val4 = new Index(1, false);
var val5 = new Index(2, false);
var val6 = new Index(3, false);
// Getting the values of
// the specified indexes
var res1 = greetings[val1];
var res2 = greetings[val2];
var res3 = greetings[val3];
var res4 = greetings[val4];
var res5 = greetings[val5];
var res6 = greetings[val6];
// Display indexes and their values
Console.WriteLine("Index:{0} Value: {1}", val1, res1);
Console.WriteLine("Index:{0} Value: {1}", val2, res2);
Console.WriteLine("Index:{0} Value: {1}", val3, res3);
Console.WriteLine("Index:{0} Value: {1}", val4, res4);
Console.WriteLine("Index:{0} Value: {1}", val5, res5);
Console.WriteLine("Index:{0} Value: {1}", val6, res6);
}
}
}
输出:
Index:^1 Value: Ahnyounghaseyo
Index:^2 Value: Ohayo
Index:^3 Value: Bonjour
Index:1 Value: Hola
Index:2 Value: Namaste
Index:3 Value: Bonjour
范例2:
// C# program to illustrate
// the use of Index constructor
using System;
namespace example {
class GFG {
// Main Method
static void Main(string[] args)
{
// Creating new indexes
// Using Index() constructor
var val1 = new Index(1, true);
var val2 = new Index(2, true);
var val3 = new Index(1, false);
var val4 = new Index(2, false);
// Checking if the specified
// index start from end or not
var res1 = val1.IsFromEnd;
var res2 = val2.IsFromEnd;
var res3 = val3.IsFromEnd;
var res4 = val4.IsFromEnd;
// Display indexes and their values
Console.WriteLine("Index:{0} Start from end?: {1}", val1, res1);
Console.WriteLine("Index:{0} Start from end?: {1}", val2, res2);
Console.WriteLine("Index:{0} Start from end?: {1}", val3, res3);
Console.WriteLine("Index:{0} Start from end?: {1}", val4, res4);
}
}
}
输出:
Index:^1 Start from end?: True
Index:^2 Start from end?: True
Index:1 Start from end?: False
Index:2 Start from end?: False