文件 test1.aspx
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; public partial class test1 : System.Web.UI.Page { /// <summary> /// 申明委托 ,在包里或者类里,public /// </summary> /// <param name="strUrl">url地址</param> /// <param name="strTitle">连接标题</param> /// <returns></returns> public delegate string DelegateSampleSum(string strUrl, string strTitle); protected void Page_Load(object sender, EventArgs e) { } protected void btn_delegateTest_Click(object sender, EventArgs e) { //利用委托调用函数 appendString DelegateSampleSum deTest = new DelegateSampleSum(appendString); lbl_show.Text = deTest("http://www.my400800.cn", "400电话"); } /// <summary> /// 定义调用委托的函数,在呼叫者里要有委托的实例(呼叫者扔出一个委托,被呼叫者给这个委托赋值) /// </summary> /// <param name="addNum"></param> /// <returns></returns> public string appendString(string strUrl, string strTitle) { string strRet = ""; strRet = string.Concat("<a href=\"", strUrl, "\">", strTitle, "</a>"); return strRet; } }
文件 test1.aspx.cs
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test1.aspx.cs" Inherits="test1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="lbl_show" runat="server" Text="显示处理结果"></asp:Label> <br /> <br /> <br /> <asp:Button ID="btn_delegateTest" runat="server" οnclick="btn_delegateTest_Click" Text="c#委托测试" /> </div> </form> </body> </html>
输出Html结果
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
Untitled Page
</title></head>
<body>
<form name="form1" method="post" action="test1.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTE2MjY5MTY1NQ9kFgICAw9kFgICAQ8PFgIeBFRleHQFLjxhIGhyZWY9Imh0dHA6Ly93d3cubXk0MDA4MDAuY24iPjQwMOeUteivnTwvYT5kZGRZZEKD2p9IkYmfo7145J/l+5q8cQ==" />
</div>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAgLxorv8AwK+3u2SA3AjPKDa3B6y3blg0YPBn1vLksJn" />
</div>
<div>
<span id="lbl_show"><a href="http://www.my400800.cn">400电话</a></span>
<br />
<br />
<br />
<input type="submit" name="btn_delegateTest" value="c#委托测试" id="btn_delegateTest" />
</div>
</form>
</body>
</html>
输出显示结果
Untitled Page
注意:
public delegate string DelegateSampleSum(string strUrl, string strTitle);
和函数
public string appendString(string strUrl, string strTitle)
{
string strRet = "";
strRet = string.Concat("<a href=\"", strUrl, "\">", strTitle, "</a>");
return strRet;
}
的返回值变量个数,变量类型必须一致,不然无法通过编译。