索引器:索引器允許類或結構的實例按照與數組相同的方式進行索引。索引器類似於屬性,不同之處在於它們的訪問器采用參數。
語法:[訪問修飾符] 數據類型 this [數據類型 標識符]
{
get{};
set{};
}
下面是視頻中的一個實例,描述的是通過索引,名稱對照片進行檢索。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication11
{
class Program
{
static void Main(string[] args)
{
Ablum MyAblum1=new Ablum (2); //創建容量為2的相冊
//創建2張照片
Photo first=new Photo ("小楚");
Photo second=new Photo ("小王");
//向相冊加載照片
MyAblum1 [0]=first ;
MyAblum1 [1]=second;
//按索引檢索
Photo testPhots=MyAblum1 [0];
Console .WriteLine (testPhots.Title );
//按名稱檢索
Photo testPhotos=MyAblum1 ["小王"];
Console .WriteLine (testPhotos .Title );
}
}
class Photo
{
private string PhotoTitle; //聲明私有變量
//建立默認值的構造函數
public Photo()
{
PhotoTitle ="楚廣明";
}
public Photo (string title) //含有一個參數的構造函數
{
PhotoTitle =title ;
}
public string Title //指定返回值
{
get {return PhotoTitle ;}
}
}
class Ablum
{
Photo [] photos; //定義數組
public Ablum ()
{
photos =new Photo[3]; //定義數組默認元素個數
}
public Ablum (int Capacity) //數組的元素任意個數
{
photos =new Photo [Capacity ];
}
public Photo this[int index] //帶有int參數的Photo索引器
{
get { //訪問
if (index <0||index >=photos .Length ) //驗證索引范圍
{
Console .WriteLine ("索引有問題");
return null ; //使用null指示失敗
}
return photos [index ]; //對於有效索引,返回請求的照片
}
set {
if (index <0||index >=photos .Length )
{
Console.WriteLine("索引有問題");
return;
}
photos [index ]=value ;
}
}
public Photo this[string title] //帶有string參數的Photo索引器
{
get {
foreach (Photo p in photos ) //遍歷數組中的所有照片
{
if (p.Title ==title ) //將照片中的標題與索引器參數進行比較
return p;
}
Console.WriteLine ("找不到");
return null ;
}
}
}
}