警惕匿名方法造成的變數共用

來源:互聯網
上載者:User

匿名方法

匿名方法是.NET 2.0中引入的進階特性,“匿名”二字說明它可以把實現內聯地寫在一個方法中,從 而形成一個委派物件,而不用有明確地方法名,例如:

static void Test()
{
  Action<string> action = delegate(string  value)
  {
    Console.WriteLine(value);
  };

  action("Hello  World");
}

但是匿名方法的關鍵並不僅於“匿名”二字。其最強大的特性就在於匿名方法形成了一個閉包,它可 以作為參數傳遞到另一個方法中去,但同時也能存取方法的局部變數和當前類中的其它成員。例如:

class TestClass
{
  private void Print(string message)
  {
     Console.WriteLine(message);
  }

  public void Test()
  {
     string[] messages = new string[] { "Hello", "World" };
    int index =  0;

    Action<string> action = (m) =>
    {
       this.Print((index++) + ". " + m);
    };

    Array.ForEach(messages,  action);
    Console.WriteLine("index = " + index);
  }
}

如上所示,在TestClass的Test方法中,action委託調用了同在TestClass類中的私人方法Print,並對 Test方法中的局部變數index進行了讀寫。在加上C# 3.0中Lambda運算式的新特性,匿名方法的使用得到 了極大的推廣。不過,如果使用不當,匿名方法也容易造成難以發現的問題。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.