简单介绍下索引和范围的简单使用。
比如我们想获得数组中的倒数第一个元素。我们可以通过C#内置函数^1
进行快速定位。返回倒数第二个元素就直接^2
以此类推。
具体如下:
string[] words = new string[]
{
"one",
"tow",
"three",
"four",
"five"
};
public string GetLastOne()
{
Index index = ^1; //返回最后一个元素
//或者直接words[^1]
return words[index];
}
假如你想返回前3个元素。那么可以使用Range,比如0..3
public string[] GetRanges()
{
//Range a = 0..3;
// var strs = words[a];
return words[0..3];
}
索引的简单定义:如类索引。
public string this[int index]
{
get {
return words[index];
} set
{
words[index] = value;
}
}
索引重载
//重载索引
public int this[string str]
{
get {
return Array.IndexOf(words, str);
}
}
最后给出整体代码和运行结果:
using System;
namespace IndexAndRange
{
class Program
{
static void Main(string[] args)
{
Point p = new Point();
Console.WriteLine("获取最后一个");
string laststr = p.GetLastOne();
Console.WriteLine(laststr);
Console.WriteLine("获取范围0-3的值");
foreach (var item in p.GetRanges())
{
Console.WriteLine(item);
}
Console.WriteLine("获取类索引值");
Console.WriteLine(p[0]);
Console.WriteLine("为索引赋值");
p[0] = "six";
Console.WriteLine(p[0]);
Console.WriteLine("获取位置信息");
Console.WriteLine(p["six"]);
Console.ReadLine();
}
}
public class Point
{
string[] words = new string[]
{
"one",
"tow",
"three",
"four",
"five"
};
public string GetLastOne()
{
Index index = ^1;
return words[index];
}
public string[] GetRanges()
{
Range a = 0..3;
var strs = words[a];
return words[0..3];
}
public string this[int index]
{
get {
return words[index];
} set
{
words[index] = value;
}
}
//重载索引
public int this[string str]
{
get {
return Array.IndexOf(words, str);
}
}
}
}