- Beginning C# 7 Hands-On:Advanced Language Features
- Tom Owsiak
- 265字
- 2021-07-02 15:29:20
Calling the delegate
Now, we have to stack up these calls; so, enter the following beneath the Summarize<double> s = FindSum; line:
s += FindRatio;
s += FindProduct;
Note that you put the next function name, FindRatio, and then the next line will be FindProduct.
Then, of course, to call it, enter the following on the very next line:
s(4, 5);
This is how you would invoke that delegate: you will call it, specify the name, and then pass in those values of 4 and 5.
The complete version of the Default.aspx.cs file for the double data type, including comments, is shown in the following code block:
//using is a directive
//System is a name space
//name space is a collection of features that our needs to run
using System;
//public means accessible anywhere
//partial means this class is split over multiple files
//class is a keyword and think of it as the outermost level of grouping
//:System.Web.UI.Page means our page inherits the features of a Page
public delegate void Summarize<T>(T x, T y);//declare generic delegate
public partial class _Default : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Summarize<decimal> s = FindSum;//assign FindSum to the delegate
s += FindRatio;//assign FindRatio to the delegate
s += FindProduct;//assign FindProduct to the delegate
s(4, 5);//invoke the delegate, causing the chain of functions to be executed
}
public void FindSum(decimal x, decimal y)
{
sampLabel.Text = $"<br>{x}+{y}={x + y}";
}
public void FindRatio(decimal x, decimal y)
{
sampLabel.Text += $"<br>{x}/{y}={x / y}";
}
public void FindProduct(decimal x, decimal y)
{
sampLabel.Text += $"<br>{x}*{y}={x * y}";
}
}
推薦閱讀
- Python程序設計教程(第2版)
- AngularJS Testing Cookbook
- Java入門經典(第6版)
- Mastering LibGDX Game Development
- Getting Started with Python Data Analysis
- 零基礎學Python網絡爬蟲案例實戰全流程詳解(高級進階篇)
- 學習正則表達式
- 深度學習:Java語言實現
- Building Android UIs with Custom Views
- JavaScript動態網頁編程
- Moodle 3 Administration(Third Edition)
- HTML5游戲開發實戰
- 體驗之道:從需求到實踐的用戶體驗實戰
- 和孩子一起學編程:用Scratch玩Minecraft我的世界
- Python數據可視化之matplotlib實踐