Marcas Technorati: C# 2.0 , métodos anónimos , anonymous methods , delegates Technorati brands: C # 2.0, anonymous methods, anonymous methods, delegates
Até aparecer o C# 2.0, a única forma de declarar delegates , era utilizar métodos normais, com um nome atribuido, que eram declarados como métodos separados. Until the C # 2.0, the only way to declare delegates, was using normal methods, with a name assigned, which was declared as separate methods.
Os métodos anónimos são essencialmente um maneira de passar um bloco de código como parâmetro, utilizando um delegate . The anonymous methods are essentially a way to move a block of code as a parameter, using a Delegate.
A utilização de métodos anónimos permite reduzir o código, pois não necessitamos de criar um método separado, logo o código fica mais limpo e intuitivo. The use of anonymous methods can reduce the code, do we need to create a separate method, once the code is cleaner and intuitive.
A especificação de um bloco de código como delegate pode ser muito útil em situações em que criar um método é desnecessário. The specification of a block of code as Delegate can be very useful in situations that create a method is unnecessary. Por exemplo no código seguinte, em que lançamos uma nova thread: For example the following code, which launched a new thread:
void StartThread() StartThread void () { ( System.Threading.Thread t1 = new System.Threading.Thread System.Threading.Thread t1 = new System.Threading.Thread (delegate() (Delegate () { ( System.Console.Write("Hello, "); System.Console.Write ( "Hello"); System.Console.WriteLine("World!"); System.Console.WriteLine ( "World!"); }); )); t1.Start(); t1.Start (); } )
De seguida está o código de uma classe, em que podemos ver a diferença entre um delegate com uma associação normal (como se fazia antes do C# 2.0), e utilizando um método anónimo (C# 2.0). Following is the code for a class, where we can see the difference between a Delegate association with a normal (as was done before the C # 2.0), and using an anonymous method (C # 2.0).
using System; using System; namespace ConsoleApplication namespace ConsoleApplication { ( //Declare a Delegate / / Declare the Delegate internal delegate void Printer(string s); Delegate internal void Printer (string s); class Program class Program { ( static void Main(string[] args) static void Main (string [] args) { ( // Instatiate the delegate type using an anonymous method: / / The delegates Instatiate type using an anonymous method: Printer p = delegate(string j) Printer Delegate p = (string j) { ( Console.WriteLine(j); Console.WriteLine (j); }; ); // Results from the anonymous delegate call: / / Results from the anonymous call Delegate: p(”The delegate using the anonymous method is called.”); p ( "The delegates using the anonymous method is called."); // The delegate instantiation using a named method “DoWork”: / / The delegates Instantiation using the method named "DoWork": p = new Printer(Program.DoWork); p = new Printer (Program.DoWork); // Results from the old style delegate call: / / Results from the old style Delegate call: p(”The delegate using the named method is called.”); p ( "The delegates named using the method is called."); } ) // The method associated with the named delegate: / / The method associated with the named Delegate: static void DoWork(string k) static void DoWork (string k) { ( Console.WriteLine(k); Console.WriteLine (k); } ) } ) } )
Como podem ver pelo código anterior, com a utilização dos métodos anónimos, não necesitamos de declarar métodos separados para associar ao delegate, basta declará-los logo na instanciação do mesmo. As you can see by the previous code, with the use of anonymous methods, no need to separate of declaring methods to associate the Delegate, simply declare them as early as the instantiation of the same.
Os métodos anónimos são apenas uma forma mais fácil de escrevermos o código, porque depois de compilado, é gerado o método separado, tal como acontecia na versão 1.1. The methods are just an anonymous easiest way of writing the code, because after compiled, the method is generated separately, as was the case in version 1.1. Do ponto de vista do código gerado fica tudo igual, apenas passamos trabalho para o compilador. From the point of view of the code generated is all the same, only spent working for the compiler. ![]()
Se gostaram deste artigo subscrevam a feed RSS do istomesmo, para ficarem actualizados sobre os últimos artigos. If you liked this article subscribe to RSS feed of istomesmo, to be updated on the latest articles.
» Subscrevam aqui a fedd RSS « Sign Up Here Fedde the RSS '
Obtenha mais informações sobre a fedd RSS aqui Learn more about the RSS Fedde here


Março 13th, 2008 at 10:47 March 13th, 2008 at 10:47 a.m.
Mais uma feature q dá muito jeito… One more feature q gives very good ...
… Mas que só complica a reutilização de código e as boas práticas Object Oriented Programming, nomeadamente Design Patterns! ... But that only complicates the reuse of code and best practices Object Oriented Programming, including Design Patterns! :-S