C # Func () Delegate

Source: Internet
Author: User

Previously, in order to be able to call a method, we must define a corresponding delegate according to this method.

Previously we defined delegate

// Delegate declaration -- Define a signature: delegate doubleMathAction (double num); class DelegateTest {// the conventional method static double Double (double input) that complies with the delegate Declaration) {return input * 2;} static void Main () {Original: // use a naming method to instantiate the delegate type MathAction ma = Double; // call the delegate instance double multByTwo = ma (4.5); Console. writeLine (multByTwo); Simplified Version 1: // use an anonymous method to instantiate the delegate type MathAction ma2 = delegate (double input) {return input * input ;}; double square = ma2 (5); Console. writeLine (square); simplified version 2: // Finally, use a Lambda expression to instantiate the delegate type MathAction ma3 = s => s * s; double cube = ma3 (4.375); Console. writeLine (cube );}}

Is there a better way to achieve this?

The answer is: yes. That is, there is a general delegate. In. NETFramework 3.5, two types of general delegate are provided.

If the method returns a value, use Func or Func <>

If the method does not return a value, use Action or Action <>

Func

T

The parameter type of the method encapsulated by this delegate.

TR

The Return Value Type of the method encapsulated by this delegate.

When using Func During delegation, you do not need to explicitly define a delegate that encapsulates only one parameter. The following example simplifies the code by instantiating Func. Instead of explicitly defining a new delegate and assigning the naming method to the delegate.


EnableUseFunc <> delegateIn this way, we write

Using System; public classLambdaExpression {public static void Main () {Func
 
  
Convert = s => s. ToUpper (); // convert lowercase letters to uppercase string name = "Dakota"; Console. WriteLine (convert (name ));}}
 

The Func delegate is a global function under the system, which is customized by the system and has multiple loads.

In addition to using the Func delegate, we also use the Labdab expression. Here I will talk about this expression.

The basic type of Lambda expressions is one of the generic Func delegation. In this wayParameter format TransferLambda expressions, instead of explicitly assigning them to delegates. In particular, because many types of methods in the System. Linq namespace have Func Parameters, so you can pass lambda expressions to these methods without explicitly instantiating Func Delegate.

The following code generates a sequence that contains all the elements on the left of 9 in the numbers array because it is the first number in the sequence that does not meet the conditions:

int[] n= { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6);

Instance 2

var firstSmallNumbers =numbers.TakeWhile((n, index) => n >= index);

This example shows how to specify multiple input parameters by including the input parameters in parentheses. This method returns all elements in the number array until a number with a value smaller than its position is encountered. Do not confuse lambda operators (=>) with operators greater than or equal to (> =.

Comparison of Three delegated statements

Using System; using System. collections. generic; using System. linq; using System. text; namespace func {// delegate declaration -- Define a signature: delegate double MathAction (double num ); public class Program {// the conventional method that complies with the delegate declaration static double Double double (double input) {return input * 2;} static void Main (string [] args) {// use a naming method to instantiate the delegate type/** write method 1. Write a dedicated delegate function and customize the delegate **/MathAction ma = Double; // note that there must be no Double () here. Otherwise, it becomes a return type and an error is reported. Here, the address of the function is specified, given is the address of the function // call the delegate double result1 = ma (4.5); // use the System Custom delegate to instantiate the delegate type/** write 2, special Delegate functions need to be written, and user-defined delegation is not required. Use System delegate **/Func
 
  
Func = Double; // call the delegate double result2 = func (4.5); // The system delegate uses lamdba to transmit parameters./** write method 3 without writing a dedicated delegate function, you also need to customize the delegate **/Func
  
   
Result = s => s * 2; // you can replace the statement block with the lamdba statement block to adapt to multiple parameters. double result3 = result (4.5); Func
   
    
Result4 = s =>{ return s * 2;}; Console. writeLine (result1); Console. writeLine (result3); Console. writeLine (result2); Console. writeLine (result4 (4.5 ));}}}
   
  
 



The same output results, but the effects of code writing are indeed different. The quality of the Code is also different. Of course, you must be responsible for your own problems. Lamdba uses simplified code, but if you are not familiar with this, it is easy to cause problems, such as starting from the source of errors. This problem is solved by writing anonymous functions. However, anonymous functions are not as easy as Lamdba. This is a compromise. See which one you prefer.

Summary:

From the Func delegate, we can see that it simplifies the tedious process of defining the delegate by ourselves, and it better integrates with the use of Lamdba. Reduces the effect of user-defined functions. At the same time, there are also some shortcomings, that is, it is not easy to find errors. The use of the Action delegate is the same as that of Func. I hope your summary will help you.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.