Simple Delegate Example

Coding:

MathOperations.cs:


1.png

Main.cs:


2.png

Result:


3.png

(1)an array of delegates委托数组:
In this code, you instantiate an array of DoubleOp delegates.Each element of the array is initialized to refer to a different operation implemented by the MathOperations class. Then, you loop through the array, applying each operation to three different values. This illustrates one way of using delegates—to group methods together into an array so that you can call several methods in a loop.
(2)delegate & method 委托和方法:
The preceding passes in the name of a delegate but without any parameters. Given that operations[i] is a delegate, syntactically:
a)operations[i] means the delegate (that is, the method represented by the delegate)
b)operationsi means call this method, passing in the value in parentheses
(3)解释:
In this method, you call:
double result = action(value);
This causes the method that is wrapped up by the action delegate instance to be called, and its return result stored in Result.
这会导致调用由action委托实例包装的方法,并将其返回的结果存储在result中。

你可能感兴趣的:(Simple Delegate Example)