废话不多说,先上配置文档
<?xml version="1.0" encoding="utf-8" ?><events> <event name="BTN1" class="DAO.DAOAction" method="BtnAction"/></events>
然后是XML解析类
class XMLContext { private Dictionary<string,string> sondic; private Dictionary<string, Dictionary<string, string>> dic; private string path;
public Dictionary<string, string> Sondic { get { return sondic; } } public Dictionary<string, Dictionary<string, string>> Dic { get { return dic; } }
public XMLContext(string path) { this.path = path; dic = new Dictionary<string,Dictionary<string,string>>(); sondic = new Dictionary<string,string>(); }
public bool XML2Dictionary() { XmlDocument xd = new XmlDocument(); xd.Load(path); XmlNodeList xnl = xd.SelectNodes("/events/event"); if (xnl.Count.Equals(0)) { throw new Exception("文档出错"); } foreach (XmlNode xn in xnl) { sondic["class"] = xn.Attributes["class"].Value; sondic["method"] = xn.Attributes["method"].Value; dic[xn.Attributes["name"].Value] = sondic; } return true; } }
继续前端控制器和应用控制器的接口
interface IController { void Init(); } interface IFrontController : IController { void FormAction(object sender, EventArgs e); } interface IApplicationController : IController { void FormAction(object sender, EventArgs e, Dictionary<string, string> dic); }
前端控制器的实现:
class FrontController : IFrontController { private static FrontController fc = null; private Dictionary<string, Dictionary<string, string>> dic = null; private IApplicationController ia = null;
public static IFrontController Instance() { if (fc == null) fc = new FrontController(); return fc; }
private FrontController () { Init(); ia = new ApplicationController(); }
public void FormAction(object sender, EventArgs e) { Control control = sender as Control; ia.FormAction(sender, e, dic[control.Name]); } public void Init() { XMLContext xml = new XMLContext("Action.xml"); xml.XML2Dictionary(); dic = xml.Dic; } }
应用控制器的实现
class ApplicationController : IApplicationController { public ApplicationController() { Init(); } public void FormAction(object sender, EventArgs e, Dictionary<string,string> dic) { Process(dic["class"], dic["method"], sender, e); } private void Process(string className, string methodName, object sender, EventArgs e) { Type type = Type.GetType(className); type.InvokeMember(methodName, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, Activator.CreateInstance(type), new object[] { sender, e }); } public void Init() { } }
使用方式:From类写个 private void xxx(object sender, EventArgs e){
FrontController.Instance.FormAction(sender, e);
}
消息到这个东西,然后再配置文档里面写你要相应的名字空间,类和方法。
这个东西比较垃圾,代码侵略性大不说还没异常处理,毕竟接触C#只有一个礼拜。实习,没项目做就写写玩的。