Вопрос

Can somebody give me example of how to use Anonymous Methods?

Do they draw backs like performance degradation of using them?

Это было полезно?

Решение

I find it very usefull to use anonymous methods to avoid global variables

Without anonymous methods:

private static Dictionary<Binding, ErrorProvider> dict = 
    new  Dictionary<Binding, ErrorProvider>();

public static void ParseBinding(Binding binding)
{

     var errorProvider = new ErrorProvider();

     dict.Add(binding, errorProvider);

     binding.Parse += new ConvertEventHandler(binding_Parse);

}

static void binding_Parse(object sender, ConvertEventArgs e)
{
     var binding = sender as Binding;
     var errorProvider = dict[binding];

     try
     {
          // some validation form e.Value
          // throws exception if not valid
     }
     catch (Exception ex)
     {
         errorProvider.SetError(binding.Control, ex.Message);
     }
}

This is really dangerous, since I need to take care for myself to remove the entries from the dictionary if not used anymore, otherwise I have a memory leak since the garbage collector will never dispose the binding or the error provider.

Now the much simpler implementation with anonymous methods:

public static void ParseBinding(Binding binding)
{
    var errorProvider = new ErrorProvider();

    binding.Parse += (sender, e) => 
        {
           try
           {
                // some validation form e.Value
                // throws exception if not valid
           }
           catch (Exception ex)
           {
               errorProvider.SetError(binding.Control, ex.Message);
           }
        };
}

Другие советы

Read MSDN: Anonymous Methods (C# Programming Guide):

Creating anonymous methods is essentially a way to pass a code block as a delegate parameter.

By using anonymous methods, you reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method.

For example, specifying a code block in the place of a delegate can be useful in a situation when having to create a method might seem an unnecessary overhead


It is an error to have a jump statement, such as goto, break, or continue, inside the anonymous method block whose target is outside the block. It is also an error to have a jump statement, such as goto, break, or continue, outside the anonymous method block whose target is inside the block.

An anonymous method cannot access the ref or out parameters of an outer scope.

No unsafe code can be accessed within the anonymous-method-block.

Also read Create Elegant Code with Anonymous Methods, Iterators, and Partial Classes

The anonymous method is defined in-line and not as a member method of any class. Additionally, there is no way to apply method attributes to an anonymous method, nor can the anonymous method define generic types or add generic constraints.

May be helpful...

http://www.dotnet-tricks.com/Tutorial/csharp/40ID180612-C-Sharp-Anonymous-Method.html

There are a couple drawbacks that while using anonymous methods. First, that you cannot use the "Edit and Continue" feature in the Visual Studio Debugger. Not allowed to make a change in the method or anonymous method while stepping through the code -- instead, you have to make your code change and restart the debugger.

The other potential issue is that, assuming the code in the anonymous method needs to be executed in response to multiple events, some developers may find themselves copying and pasting the code in several places of their application, thus ignoring the general rule of code re-use.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top