C#索引器的使用,类和接口中的索引器this

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());
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值