About delegation

A delegate is simply an object that can pass a method as a parameter. It can be said to be an interface, but it constrains the signature pointing to the method.

Example: define a delegate (delegates can be defined outside the class like interfaces)

delegate int Wt(int x); any return value and parameter same as this delegate can be called

Such as:

static int Double(int i){ return i*2;}

Example:

Wt wt=new Wt(Double);  或者 Wt wt=Double;

transfer:

int result=wt(2); result result = 4;

Function: can realize plug-in programming (reduce repetitive code)

delegate int Wt(int x);

class Test{

  static int Double(int i){ return i*2;}//整数double

  static int Square(int i){ return i^2;}//Integer square root

  static void Main(String[] args){

    int[] values=[1,2,3,4];

    Cj.WtCj(values,Double);

    //values ​​result is [2,4,6,8] 

    Cj.WtCj(values,Square);

    //values ​​result is [1,4,9,16] 

  }

}

class Cj{

  public static void WtCj(int[] values,Wt wt){

    for(int i = 0; i<values.length;i++){

      values[i]=wt(values[i]);

    }

  }

}

The above Cj is fixed, and the function implements the Double function of the integer, which is equivalent to a simple plug-in.

If you don't understand it yet, assume you don't need to delegate. Written like:

class Cj{

  public static void WtCj(int[] values){

    for(int i = 0; i<values.length;i++){

      values[i]=wt(Double([i]));//Directly use the method to convert the numbers in the values ​​array*2

    }

  }

}

Although the above can achieve repeated calls, it is only applicable to the Double function of integers. For example, functions such as squaring the values ​​array cannot be implemented, and additional methods need to be written again.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325379617&siteId=291194637