c# 匿名方法學習

來源:互聯網
上載者:User

1. 匿名方法簡介
    匿名方法允許我們以一種“內聯”的方式來編寫方法代碼,將代碼直接與委託執行個體相關聯,從而使得委託執行個體化的工作更加直觀和方便。

2.匿名方法的幾個相關問題:

2.1 參數列表
    匿名方法可以在delegate關鍵字後跟一個參數列表(可以不指定),後面的代碼塊則可以訪問這些參數:
addButton.Click += delegate(object sender, EventArgs e) {MessageBox.Show(((Button)sender).Text);};

注意“不指定參數列表”與“參數列表為空白”的區別

addButton.Click += delegate {…} // 正確!
addButton.Click += delegate() {…} // 錯誤!

2.2 傳回值
    如果委託類型的傳回值類型為void,匿名方法裡便不能返回任何值;如果委託類型的傳回值類型不為void,匿名方法裡返回的值必須和委託類型的傳回值相容:

delegate int MyDelegate();
MyDelegate d = delegate{
    ……
    return 100;
};

delegate void MyDelegate();
MyDelegate d = delegate{
    ……
    return;
};

2.3 外部變數
    一些局部變數和參數有可能被匿名方法所使用,它們被稱為“匿名方法的外部變數”。外部變數的生存期會由於“匿名方法的捕獲效益”而延長——一直延長到委託執行個體不被引用為止。

static void Foo(double factor)
{
    Function f=delegate(int x)
   {
        factor +=0. 2; // factor為外部變數
        return x * factor;
    };
    Invoke(f); // factor的生存期被延長
}

3.委託類型的推斷
    C#2.0 允許我們在進行委託執行個體化時,省略掉委託類型,而直接採用方法名,C#編譯器會做合理的推斷。
• C# 1.0中的做法:

addButton.Click += new EventHandler(AddClick);
Apply(a, new Function(Math.Sin));

• C# 2.0中的做法:

addButton.Click += AddClick;
Apply(a, Math.Sin);

4 匿名方法機制
    C# 2.0中的匿名方法僅僅是通過編譯器的一層額外處理,來簡化委託執行個體化的工作。它與C# 1.0的代碼不存在根本性的差別。

4.1 靜態方法中的匿名方法

public delegate void D();
static void F()
{
    D d = delegate { Console.WriteLine("test"); }
}

上面的代碼被編譯器轉換為:

static void F()
 {
    D d = new D(<F>b__0);
}

static void <F>b__0()
 {
    //函數名和類名可能不同
    Console.WriteLine("test");
}

4.2 執行個體方法中的匿名方法

class Test
 {
    int x;
    void F()
    {
        D d = delegate { Console.WriteLine(this.x); };
    }
}

上面的代碼被編譯器轉換為:

void F()
 {
    D d = new D(<F>b__0);
}
void <F>b__0()
 {
    Console.WriteLine(this.x);
}

4.3 匿名方法中的外部變數

void F()
 {
    int y = 123;
    D d = delegate { Console.WriteLine(y); };
}

轉自:http://blog.csdn.net/happyhippy/archive/2007/03/20/1534812.aspx

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.