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中。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容