Java Delegation for Object Oriented Fundamentals and lambda

  • 2021-12-11 07:37:55
  • OfStack

Delegates define types that specify specific method signatures. You can assign a method (static or instance) that satisfies this signature to a variable of that type, and then call the method directly (with appropriate parameters), or pass it as a parameter itself to another method before calling. The following example demonstrates the use of delegates.


using System;
using System.Linq;

public class Program
{
    public delegate string Reverse(string s);

    static string ReverseString(string s)
    {
        return new string(s.Reverse().ToArray());
    }

    static void Main(string[] args)
    {
        Reverse rev = ReverseString;

        Console.WriteLine(rev("a string"));
    }
}
public delegate string Reverse(string s); Line creates a delegate type for a specific signature, in this case a method that accepts and returns string parameters. static string ReverseString(string s) Method has exactly the same signature as the defined delegate type and is used to implement the delegate. Reverse rev = ReverseString; Rows display variables that can assign methods to corresponding delegate types. Console.WriteLine(rev("a string")); Row demonstrates how to use variables of delegate type to call delegates.

To simplify the development process,. NET contains a set of delegate types that programmers can reuse without creating new ones. These include Func<> , Action<> And Predicate<> Can be used in various locations of. NET API without defining a new delegate type. Of course, from the signatures of these three people, we can see that there are some differences between them, which mainly affect their intended use:

Action<> Used in cases where you need to use delegate parameters to perform operations. Func<> Usually used in the case of existing transformations, that is, when delegate parameters need to be converted to other results. The best example is projection. Predicate<> Used in cases where you need to determine whether a parameter meets a delegate condition. It can also be written as Func < T, bool > .

Func is now available < > Delegate instead of custom type to rewrite the above example. The program will continue to run as usual.


using System;
using System.Linq;

public class Program
{
    static string ReverseString(string s)
    {
        return new string(s.Reverse().ToArray());
    }

    static void Main(string[] args)
    {
        Func<string, string> rev = ReverseString;

        Console.WriteLine(rev("a string"));
    }
}

For this simple example, defining methods outside the Main method seems redundant. Thus. NET Framework 2.0 introduces the concept of anonymous delegates. With its support, you can create "inline" delegates without specifying any other types or methods. Simply inline the definition of the delegate in the desired location.

For example, you want to switch and use anonymous delegates to filter out even-numbered lists and print them to the console.


using System;
using System.Collections.Generic;

public class Program
{
    public static void Main(string[] args)
    {
        List<int> list = new List<int>();

        for (int i = 1; i <= 100; i++)
        {
            list.Add(i);
        }

        List<int> result = list.FindAll(
          delegate (int no)
          {
              return (no % 2 == 0);
          }
        );

        foreach (var item in result)
        {
            Console.WriteLine(item);
        }
    }
}

As you can see, the body of this delegate is just one set of expressions, and so are all other delegates. But it is not defined separately, but when calling List < T > . FindAll method.

However, even with this method, there is still a lot of code that can be discarded. At this point, you need to use the lambda expression.

The lambda expression (or simply "lambda") was first introduced in C # 3.0 as the core building block for language integrated queries (LINQ). This expression is just a more convenient syntax for using delegates. They declare the signature and method body, but do not have their own formal identity before being assigned to the delegate. Unlike delegates, they can be assigned as the left side of the event registration or directly in various LINQ clauses and methods.

Since an lambda expression is just another way to specify a delegate, you should be able to rewrite the above example to use an lambda expression instead of an anonymous delegate.


using System;
using System.Collections.Generic;

public class Program
{
    public static void Main(string[] args)
    {
        List<int> list = new List<int>();

        for (int i = 1; i <= 100; i++)
        {
            list.Add(i);
        }

        List<int> result = list.FindAll(i => i % 2 == 0);

        foreach (var item in result)
        {
            Console.WriteLine(item);
        }
    }
}

In the previous example, the Lambda expression used is i = > i% 2 = = 0. Again, it is only a very convenient syntax for using delegates, so its actual behavior is the same as when using anonymous delegates.

Again, lambda is just a delegate, which means it works well as an event handler, as shown in the following code snippet.


public MainWindow()
{
    InitializeComponent();

    Loaded += (o, e) =>
    {
        this.Title = "Loaded";
    };
}

The += operator in this context is used to subscribe to events.

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: