|
示例一:委托被同时映射到静态方法和实例方法,并分别返回特定的信息
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class delegate1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SampleClass sc = new SampleClass();
// Map the delegate to the instance method:
Del d = sc.InstanceMethod;
d();
// Map to the static method:
d = SampleClass.StaticMethod;
d();
}
}
delegate void Del();
class SampleClass
{
public void InstanceMethod()
{
HttpContext.Current.Response.Write("A message from the instance method.");
}
static public void StaticMethod()
{
HttpContext.Current.Response.Write("A message from the static method.");
}
}
示例二
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
delegate void Del(int i, double j);
public partial class _Default :Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Del d = MultiplyNumbers;
Response.Write("Invoking the delegate using 'MultiplyNumbers':");
for (int i = 1; i <= 5; i++)
{
d(i, 2);
}
}
}
protected void MultiplyNumbers(int m, double n)
{
HttpContext.Current.Response.Write(m * n + " ");
}
} |
|