Beginning C# 7 Hands-On:Advanced Language Features
上QQ阅读APP看书,第一时间看更新

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}";
}
}