using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 索引器重载
{
class Program
{
static void Main(string[] args)
{
FailSofArray fs = new FailSofArray(5);
for (int i = 0; i < fs.Length; i++)
{
fs[i] = i;
}
Console.WriteLine("fs[1]:"+fs[1]);
Console.WriteLine("fs[2]:" + fs[2]);
Console.WriteLine("fs[1.1]:" + fs[1.1]);
Console.WriteLine("fs[1.6]:" + fs[1.6]);
}
}
class FailSofArray
{
int[] a;
public int Length;
public bool ErrFlag;
public FailSofArray(int size)
{
a = new int[size];
Length = size;
}
public int this[int index]
{
get {
if (ok(index))
{
ErrFlag = false;
return a[index];
}
else
{
ErrFlag = true;
return 0;
}
}
set
{
if (ok(index))
{
a[index] = value;
ErrFlag = false;
}
else
ErrFlag = true;
}
}
public int this[double idx]
{
get { int index;
if ((idx - (int)idx) < 0.5) index = (int)idx;
else
index = (int)idx + 1;
if (ok(index))
{
ErrFlag = false;
return a[index];
}
else
{
ErrFlag = true;
return 0;
}
}
set
{
int index;
if ((idx - (int)idx) < 0.5) index = (int)idx;
else index = (int)idx + 1;
if (ok(index))
{
a[index] = value;
ErrFlag = false;
}
else
ErrFlag = true;
}
}
private bool ok(int index)
{
if (index >= 0 & index < Length)
return true;
return false;
}
}
}
索引器体内通过get 和 set 进行存取。
可以在里面进行判断,给数组赋值 进入set 取值进入get
另外多维索引也是一样,索引不需要底层数组,他只是对相应的类进行检查。