- 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}";
}
}
推薦閱讀
- Objective-C Memory Management Essentials
- 網店設計看這本就夠了
- Web程序設計(第二版)
- Python編程從0到1(視頻教學版)
- 領域驅動設計:軟件核心復雜性應對之道(修訂版)
- Node.js:來一打 C++ 擴展
- OpenGL Data Visualization Cookbook
- 深入理解C指針
- Java Web應用開發項目教程
- SQL Server 2016 從入門到實戰(視頻教學版)
- Apache Solr PHP Integration
- MongoDB Cookbook
- 軟件設計模式(Java版)
- Mapping with ArcGIS Pro
- Backbone.js Patterns and Best Practices