在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
有在论坛看见一帖,《C#用什么方法可以减少或不使用switch》
Insus.NET的解决方法,是使用工厂方法来处理,可以创建一个工厂接口,然后每个方法设计为一个工厂类,并实现工厂接口。 工厂接口:
IGetFactory
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for IGetFactory /// </summary> namespace Insus.NET { public interface IGetFactory { string GetResult(); } }
GetFactory
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for GetFactory /// </summary> namespace Insus.NET { public class GetFactory : IGetFactory { public GetFactory() { // // TODO: Add constructor logic here // } public string GetResult() { return "get"; } } }
GetTestFactory
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for GetTestFactory /// </summary> namespace Insus.NET { public class GetTestFactory : IGetFactory { public GetTestFactory() { // // TODO: Add constructor logic here // } public string GetResult() { return "gettest"; } } }
GetSetFactory
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for GetSetFactory /// </summary> namespace Insus.NET { public class GetSetFactory : IGetFactory { public GetSetFactory() { // // TODO: Add constructor logic here // } public string GetResult() { return "getset"; } } }
View Code
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Insus.NET; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } public string Exec(string mothedName) { string ret = ""; //switch (mothedName) //{ // case "get": // ret = get(); // break; // case "get1": // ret = gettest(); // break; // //..... // case "testget": // ret = getrset(); // break; //} IGetFactory get = new GetTestFactory(); //这里是实现工厂类 ret = get.GetResult(); return ret; } //public string get() //{ // return "get"; //} //public string gettest() //{ // return "gettest"; //} //public string getrset() //{ // return "getset"; //} }
IGetFactory get = new GetTestFactory(); //这里是实现工厂类
Reflection
IGetFactory get = (IGetFactory)Assembly.Load("App_Code").CreateInstance("Insus.NET." + mothedName + "Factory");
View Code
IGetFactory get = (IGetFactory)Assembly.Load("程序集名称").CreateInstance("Insus.NET." + mothedName + "Factory");
|
请发表评论