using System;
public class IndexMachine
{
public long[] arr = new long[100];
//通过索引器可以存取类的实例的数组成员,操作方法与数组相似。
public long this[int index]//申明索引器
{
get
{
if(index < 0 || index >=100)
{
return 0;
}
return arr[index];
}
set
{
if(!(index < 0 || index >=100))
{
arr[index] = value;
}
}
}
public long pow(int x, int y)
{
return (long)Math.Pow(x,y);
}
}
//接口索引器与类索引器的区别有两个:
// 一是接口索引器不使用修饰符;
// 二是接口索引器只包含访问器get或set,没有实现语句
public interface IAddres
{
//申明索引器
string this[int index]
{
get;
set;
}
string getAddres();
}
public class Addres:IAddres
{
string []add = new string[5];
public string this[int index]
{
get
{
if(index<0||index>=5)
{
return add[0];
}
else
return add[index];
}
set
{
if(!(index<0 || index >=5))
{
add[index]= value;
}
else
{
add[0] = value;
}
}
}
public string getAddres()
{
string s = add[0] + "省";
s += add[1] + "市";
s += add[2] + "区";
s += add[3] + "镇";
s += add[4] + "街道";
return s;
}
}
public class Student
{
public string name;
public Addres add = new Addres();
public Student(params string[] info)
{
name = info[0];
for(int i = 0; i< info.Length -1; i++ )
{
//通过索引器赋值
add [i] = info[i+1];
}
}
public string Answer()
{
string s = name;
s += add.getAddres();
return s;
}
}
public class IndexMachineTest
{
public static void Main(string[] args)
{
/*
IndexMachine inm = new IndexMachine();
for(int i=0; i< 100; i++)
{
//通过索引器赋值
inm[i] = inm.pow(i+1,2);
}
Console.WriteLine("索引器测试");
for(int i=0; i< 100; i++)
{
Console.Write("inm[i] = {0}\t",inm[i]);
}
*/
Student s = new Student(new string[]{"wjc","四川","成都","高新","中和","朝阳"});
Console.WriteLine(s.Answer());
}
}
C#索引器的使用,类和接口中的索引器this
最新推荐文章于 2023-03-19 09:42:12 发布