索引器類似屬性,不過是針對數組的,索引器的使用示例如下所示:
namespace ConsoleApplication9Indexer { class Class1 { private string[] Strs = new string[100]; public string this[int i] { get { return Strs[i]; } set { Strs[i] = value; } } private int[,] Ints = new int[10,10]; public int this[int i,int j] { get { return Ints[i,j]; } set { Ints[i,j] = value; } } } class Program { static void Main(string[] args) { Class1 Tc = new Class1(); Tc[1] = "sjkf"; Console.WriteLine(Tc[1]); Tc[0,0] = 10; Console.WriteLine(Tc[0,0]); } } }
namespace ConsoleApplication9Indexer { public interface Inter1 { string this[int i] { get; set; } } public interface Inter2 { string this[int j] { get; set; } } public interface Inter3 { string this[int i] { get; set; } } class Class2 : Inter1,Inter2,Inter3 { private string[] names = new string[100]; private string[] sexs = new string[100]; private string[] Adds = new string[100]; string Inter1.this[int i] { get { return names[i]; } set { names[i] = value; } } string Inter2.this[int j] { get { return sexs[j]; } set { sexs[j] = value; } } public string this[int i] { get { return Adds[i]; } set { Adds[i] = value; } } } static void Main(string[] args) { Class2 Ts = new Class2(); Inter1 Inters1 = (Inter1)Ts; Inters1[11] = "whjhd"; Console.WriteLine(Inters1[11]); Inter2 Inters2 = (Inter2)Ts; Inters2[67] = "what a fucking day"; Console.WriteLine(Inters2[67]); } }