根據傳進來不同的值,呼叫不同的方法
View Code
protected void btn_SwitchClick(object sender, EventArgs e) { string result = ""; switch (ddlMethod.SelectedValue) { case "A": result = SwitchTest.GetA(); break; case "B": result = SwitchTest.GetB(); break; case "C": result = SwitchTest.GetC(); break; default: result = ddlMethod.SelectedValue + "方法找不到"; break; } ltrResult.Text = result; }
下面利用反射機制實現,首選需要一個自定義屬性類
View Code
public class ActionMethodAttribute:Attribute { public string ActionTypeName; public ActionMethodAttribute(string typeName) { this.ActionTypeName = typeName; } }
然後定義一個基類
View Code
public abstract class GenericBLL { public Hashtable GetMethodAttribute<T>(T t) { Hashtable ht = new Hashtable(); Hashtable obj = CacheHandler<Hashtable>.GetCache(t.ToString()); if (obj == null) { Type type = t.GetType(); foreach (MethodInfo mi in type.GetMethods()) { ActionMethodAttribute[] mis = (ActionMethodAttribute[])mi.GetCustomAttributes(typeof(ActionMethodAttribute), false); foreach (ActionMethodAttribute actionMethodAttribute in mis) { string actionName = actionMethodAttribute.ActionTypeName; ht.Add(actionName, mi); } } CacheHandler<Hashtable>.SetCache(t.ToString(), ht); } else { ht = (Hashtable)obj; } return ht; } /// <summary> /// return message; /// </summary> /// <param name="actionName"></param> /// <returns></returns> public string DoAction(string actionName) { string message; Hashtable ht = GetMethodAttribute(this); if (ht.Contains(actionName)) { message = ((MethodInfo)ht[actionName]).Invoke(this, new object[] { }).ToString(); } else { message = string.Format("{0} Not Defined.!", actionName); //throw new Exception(errmsg); } return message; } }
實現類繼承,
View Code
public class ReflectTest:GenericBLL { [ActionMethod("A")] public string GetA() { return "呼叫的A"; } [ActionMethod("B")] public string GetB() { return "呼叫的B"; } [ActionMethod("C")] public string GetC() { return "呼叫的C"; } }
具體的呼叫
View Code
protected void btn_ReflectClick(object sender, EventArgs e) { string result = ReflectTest.DoAction(ddlMethod.SelectedValue); ltrResult.Text = result; }
ASPX中的程式碼如下
View Code
選D會提示沒有D方法 <asp:DropDownList ID="ddlMethod" runat="server"> <asp:ListItem Text="A" Value="A"> </asp:ListItem> <asp:ListItem Text="B" Value="B"> </asp:ListItem> <asp:ListItem Text="C" Value="C"> </asp:ListItem> <asp:ListItem Text="D" Value="D"> </asp:ListItem> </asp:DropDownList> <br /> <asp:Button ID="btnInvoke" Text="Switch" OnClick="btn_SwitchClick" runat="server" /> <asp:Button ID="btnInvokeR" Text="Reflect" OnClick="btn_ReflectClick" runat="server" /> <br> <asp:Literal ID="ltrResult" runat="server" />
原始碼下載: ActionMethod.rar