7-7.cs

来自「java基础方面的一些实例代码」· CS 代码 · 共 58 行

CS
58
字号
using System;
namespace TestOfIndexer
{
	public class IndexerTesting
	{
		int theInt;
		string theStr;                // 与int型索引器相关字段
		int [] IntArray = new int[3]; // 与char型索引器相关字段
	    // 构造函数
		public IndexerTesting()
		{ }
		public IndexerTesting(int[] iArr)
		{
				IntArray = iArr;
		}
		// 属性
		public int IntAccessor
		{
			get{return theInt;}
			set{ theInt = System.Math.Abs(value);}
		}
		public string TheString
		{
			get { return theStr;}
			set{ theStr = value + DateTime.Now;}
		}
		// 索引器,可以象访问数组一样访问对象的成员
		// 索引器与属性类似
		// int型索引器
		public int this[int ind]
		{
			get { return IntArray[ind];}
		}
		// char型索引器
		public int this[ char chInStr]
		{
			get { return theStr.IndexOf(chInStr);}
		}
	}
	public class Test
	{
		static void Main(string[] args)
		{
			int [] iArr = {2,3,4};
			IndexerTesting IndTesting = new IndexerTesting(iArr);
			// 调用int型索引器
			Console.WriteLine("IntArray[{0}] is {1} ",2,IndTesting[2]);
			IndTesting.IntAccessor = -365;
			Console.WriteLine(IndTesting.IntAccessor);
			IndTesting.TheString = "Create time:";
			Console.WriteLine(IndTesting.TheString);
			// 调用char型索引器
			Console.WriteLine("-是第{0}个字符,",(IndTesting['-']+1));
			Console.WriteLine("C是第{0}个字符,",(IndTesting['C']+1));
		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?