⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 testindexer.cs

📁 yongle jpscxsd j cxksk xdkl sna
💻 CS
字号:
using System;

namespace Example_2
{
	/// <摘要>
	/// 该程序演示索引器的用法
	/// </摘要>
	
	//   Photo 表示照片
	//   这里的简单实现只包含标题。 更加实用的版本
	//   可以包括文本描述和指向包含照片的文件链接。
	class Photo
	{
		class Delegates
		{

		}
	
		string _title;

		public Photo(string title)
		{
			this._title = title;
		}

		public string Title
		{
			get
			{
				return _title;
			}
		}
	}

	// 此类表示相册,即照片的集合
	class Album
	{
		//用于存储照片的数组
		Photo[] photos;

		// 用户创建相册时必须指定相册可以存放照片的张数。
		// 为数组分配存储照片所需的确切大小。
		public Album(int capacity)
		{
			photos = new Photo[capacity];
		}

		//   传递的索引用于对照片数组进行检索。
		public Photo this[int index]
		{
			get
			{
				// 验证索引范围
				if (index < 0 || index >= photos.Length)
				{
					Console.WriteLine("索引无效");
					// 使用 null 指示失败
					return null;
				}

				// 对于有效索引,返回请求的照片
				return photos[index];
			}

			set
			{
				// 验证索引范围
				if (index < 0 || index >= photos.Length)
				{
					Console.WriteLine("索引无效");

					return;
				}

				//对于有效索引,向数组加载新的照片
				photos[index] = value;
			}
		}

		//   允许按标题查找照片
		public Photo this[string title]
		{
			get
			{
				// 循环遍历数组中的所有照片
				foreach (Photo p in photos)
				{
					// 将照片的标题与索引器参数进行比较
					if (p.Title == title)
						return p;
				}
				Console.WriteLine("未找到");

				// 使用 null 指示失败
				return null;
			}
		}
	}

	class TestIndexer
	{
		/// <摘要>
		/// 应用程序的主入口点。
		/// </摘要>
		[STAThread]
		static void Main(string[] args)
		{
			// 创建容量为 3 的相册
			Album friends = new Album(3);

			// 创建 3 张照片
			Photo first = new Photo("Jenn");
			Photo second = new Photo("Smith");
			Photo third = new Photo("Mark");

			// 向相册加载照片
			friends[0] = first;
			friends[1] = second;
			friends[2] = third;

			// 按索引进行检索
			Photo obj1Photo = friends[2]; 
			Console.WriteLine(obj1Photo.Title);

			// 按名称进行检索
			Photo obj2Photo = friends["Jenn"]; 
			Console.WriteLine(obj2Photo.Title);
		}		
	}
}

⌨️ 快捷键说明

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