?? testindexer.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 + -