首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 實用但易被遺忘的特性與技巧 (二) 匿名方法與索引器

     編輯:關於C語言

匿名方法

C# 2.0 引入匿名方法,適合邏輯簡單、僅用一次的委派場景,避免額外定義命名方法:

delegate void Dele();
class Program
{
    static void Main()
    {
        Dele d = delegate() { Console.WriteLine("這是一個匿名方法!"); };
        d.Invoke();
    }
}

輸出:「這是一個匿名方法!」

索引器

索引器讓物件像陣列一樣透過索引存取元素。定義語法類似屬性,但帶參數:

class PersonNames
{
    List names = new List();
    public string this[int index]
    {
        get { return names[index]; }
        set { names.Add(value); }  // 此處示範邏輯,實際應為 names[index] = value;
    }
}

class Program
{
    static void Main()
    {
        PersonNames names = new PersonNames();
        names[0] = "微軟";
        names[1] = "谷歌";
        names[2] = "百度";
        for (int i = 0; i < 3; i++) Console.WriteLine(names[i]);
    }
}

輸出:微軟、谷歌、百度。

注意

索引器不支援 foreach,若需迭代請實作 IEnumerable 介面。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved