普通委托
public partial class view_fees : System.Web.UI.Page
{
/// <summary>
/// 声明一个委托
/// </summary>
/// <param name="type"></param>
/// <param name="code"></param>
/// <param name="list"></param>
delegate void UpdateAuditingDelegate(string type, string code, ArrayList list);//
//
//
}
protected void Butsh01_Command(object sender, CommandEventArgs e)
{
UpdateAuditingDelegate d = new UpdateAuditingDelegate(cf.Out_Update);
//
}
public void Out_Update(string type, string code, ArrayList list)
{
//
}
ArrayList temp = new ArrayList();
temp.Clear();
if (temp.Count > 0)
{
d(e.CommandName, crcode, temp);
}代理的声明使用以下语法: delegate void SimpleDelegate();
实例化一个代理:
class Test
{
static void F()
{
System.Console.WriteLine("hello world");
}
static void Main()
{
SimpleDelegate d = new SimpleDelegate(F);//将方法压入
d();//通过代理;
F();//不通过代理;
}
}
void MultiCall(SimpleDelegate d, int count)
{
for (int i = 0; i < count; i++)
d();
} 代理在我看来好比是对象要执行一件事她不直接地调用这个方法,而是通过一个中间人去调用它。
************************************************************
如何用指向基类的对象调用子类的成员函数?
在这里程序员是不是点怀恋指针了,不过在c#中这样的功能完全也可实现的,使用一个单独的代理我们可以完成这项功能。
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;
namespace DelegatesCS
{
public class Wisdom //包含代理的类
{
public delegate string GiveAdvice();
public string OfferAdvice(GiveAdvice Words)
{
return Words();
}
}
public class Parent //基类
{
public virtual string Advice()
{
return("Listen to reason");
}
~Parent() {}
}
public class Dad: Parent //子类
{
public Dad() {}
public override string Advice()
{
return("Listen to your Mom");
}
~Dad()
{}
}
public class Mom: Parent //子类
{
public Mom()
{}
public override string Advice()
{
return("Listen to your Dad");
}
~Mom()
{}
}
public class Daughter //不继承与基类的类
{
public Daughter()
{}
public string Advice()
{
return("I know all there is to life");
}
~Daughter()
{}
}
public class Test
{
public static string CallAdvice(Parent p)//使用基类
{
Wisdom parents = new Wisdom();
Wisdom.GiveAdvice TeenageGirls = new Wisdom.GiveAdvice(p.Advice);//将Advice方法委托给TeenageGirls委托对象
return(parents.OfferAdvice(TeenageGirls));
}
public static void Main()
{
Dad d = new Dad();
Mom m = new Mom();
Daughter g = new Daughter(); //以下两个为衍于基类的类 
Console.WriteLine(CallAdvice(d));
Console.WriteLine(CallAdvice(m));
//以下为未衍于基类的类,如果调用将出错。
//Console.WriteLine(CallAdvice(g));
}
} 
} 

浙公网安备 33010602011771号