iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 23
0
Software Development

我要轉職成 C# / .NET 工程師系列 第 23

Indexer索引函式(索引子)-把物件當成陣列使用

若想把物件當成陣列來使用,C#1.0開始就有提供Indexer,讓我們在類別中實作索引函式,達到物件當成陣列用的目的

https://ithelp.ithome.com.tw/upload/images/20191009/20120420OL9noGT67y.png

實作Indexer索引函式

Indexer第一次看到時覺得還蠻有趣的,雖然後來有List跟泛型可以用,不過Indexer也算是一種傳入方式

撰寫方式有點像昨天說的property一樣有set、get和value,如以下:

public class 會員
{
    public string 會員ID { get; set; }
    public string 名稱 { get; set; }
}
public class 會員名冊
{
    private List<會員> 名冊 = new List<會員>();

    public 會員 this [int index]
    {
        get
        {
            if (index >= 0 && index < 名冊.Count)
            {
                return 名冊[index];
            }
            else
            {
                return null;
            }
        }
        set
        {
            if (index >= 0 && index < 名冊.Count)
            {
                 名冊[index] = value;
            }
            if(index == 名冊.Count)
            {
                名冊.Add(value);
            }                    
        }

    }

}

https://ithelp.ithome.com.tw/upload/images/20191009/20120420jAH0w1mC9P.png

多載傳入型別

索引函式可以多載,除了剛剛寫的this [int index]索引函式,我們還可以在類別中再加入一個傳入值是string的索引函式
https://ithelp.ithome.com.tw/upload/images/20191009/201204203BjxLyovyj.png

https://ithelp.ithome.com.tw/upload/images/20191009/20120420ueLq558Na1.png


上一篇
Property翻譯成內容函式,比翻成屬性還要好懂
下一篇
C#的var、dynamic、const、readonly
系列文
我要轉職成 C# / .NET 工程師34
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言