在開發asp.net過程中,Insus.NET較喜歡寫UserControl(使用者控制元件),因為它就是一個靈活的物件。可以在網頁隨意變換與控制。此次Insus.NET想說的問題,可看如下說明,就比如前一篇《觀察者模式與使用者控制元件之間的互動 》,其中UserD與UserC兩個使用者控制元件可以互動。這兩個使用者控制元件都寫了event(事件),delegate(委託)。這部分可以重構一下。把他們寫成一個interface(介面),也就是寫成一個事件介面。此篇另寫例子,讓我們學會如何在asp.net開發過程中寫事件介面與應用,非以前篇作重構與修改。
ITransmitable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for ITransmitable
/// </summary>
public delegate void TransmitEventHandler(object sender,string value);
public interface ITransmitable
{
//事件介面
event TransmitEventHandler Transmit;
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for ITransmitable
/// </summary>
public delegate void TransmitEventHandler(object sender,string value);
public interface ITransmitable
{
//事件介面
event TransmitEventHandler Transmit;
}
兩個使用者控制元件分別實作這個介面。UserA,
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class UserA : System.Web.UI.UserControl, ITransmitable //實作介面
{
protected void Page_Load(object sender, EventArgs e)
{
}
public event TransmitEventHandler Transmit;
protected void Button1_Click(object sender, EventArgs e)
{
if (Transmit != null)
Transmit(this, this.TextBox1.Text);
this.TextBox1.Text = string.Empty;
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class UserA : System.Web.UI.UserControl, ITransmitable //實作介面
{
protected void Page_Load(object sender, EventArgs e)
{
}
public event TransmitEventHandler Transmit;
protected void Button1_Click(object sender, EventArgs e)
{
if (Transmit != null)
Transmit(this, this.TextBox1.Text);
this.TextBox1.Text = string.Empty;
}
}
UserB使用者控制元件實作介面,
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class UserB : System.Web.UI.UserControl, ITransmitable
{
protected void Page_Load(object sender, EventArgs e)
{
}
public event TransmitEventHandler Transmit;
protected void Button1_Click(object sender, EventArgs e)
{
if (Transmit != null)
Transmit(this, this.TextBox1.Text);
this.TextBox1.Text = string.Empty;
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class UserB : System.Web.UI.UserControl, ITransmitable
{
protected void Page_Load(object sender, EventArgs e)
{
}
public event TransmitEventHandler Transmit;
protected void Button1_Click(object sender, EventArgs e)
{
if (Transmit != null)
Transmit(this, this.TextBox1.Text);
this.TextBox1.Text = string.Empty;
}
}
例子演示:
Demo程式碼:
http://download.cnblogs.com/insus/ASPDOTNET/EventInterfaceAndUserControlInteractive.rar