C# Generic 方法
WebForm7.cs |
using System; using System.Collections; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication9 { public partial class WebForm7 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ArrayList AList = new ArrayList(); TextBox TextBoxObj = new TextBox(); TextBoxObj.Text = "Generic Textbox"; AList.Add(TextBoxObj); Label LabelObj = new Label(); LabelObj.Text = "Generic Label"; AList.Add(LabelObj); LiteralControl LiteralControlObj = new LiteralControl("<p>Generic Literal Control</p>"); AList.Add(LiteralControlObj); DropDownList DropDownListObj = new DropDownList(); DropDownListObj.Items.Add(new ListItem("Generic Text", "Generic Value")); AList.Add(DropDownListObj); foreach (object item in AList) test<object>(item); } void test<T>(T t) { if (t.GetType() == typeof(System.Web.UI.WebControls.Label)) { object LabelObject = t; Label lbl = (Label)LabelObject; PlaceHolder1.Controls.Add(lbl); } else if (t.GetType() == typeof(System.Web.UI.WebControls.TextBox)) { object TextBoxObject = t; TextBox tb = (TextBox)TextBoxObject; PlaceHolder1.Controls.Add(tb); } else if (t.GetType() == typeof(System.Web.UI.LiteralControl)) { object LiteralControlObject = t; LiteralControl lc = (LiteralControl)LiteralControlObject; PlaceHolder1.Controls.Add(lc); } } } } |