欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#可以减少或不使用switch有什么方法

程序员文章站 2024-03-04 17:07:17
insus.net的解决方法,是使用工厂方法来处理,可以创建一个工厂接口,然后每个方法设计为一个工厂类,并实现工厂接口。 工厂接口: 复制代码 代码如下: igetfact...
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();
}
}

get工厂类
复制代码 代码如下:

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";
}
}
}

gettest类
复制代码 代码如下:

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";
}
}
}

以及getset类
复制代码 代码如下:

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";
//}
}

15:50修改补充如下
上面的最终代码,无传入参数mothedname,怎样办,我们可以虑一下反射,如果改为反射击,那传入的参数需要规范一下方可以:
"get" >>"get";
"get1" >>"gettest"
"testget" >> "getset"
这样一改之后,就可以使用反射语法了,可以把
复制代码 代码如下:

igetfactory get = new gettestfactory(); //这里是实现工厂类

改为(下面是asp.net的应用):
复制代码 代码如下:

igetfactory get = (igetfactory)assembly.load("app_code").createinstance("insus.net." + mothedname + "factory");

如果在非asp.net下,可以把"app_code"改为"程序集名称":
复制代码 代码如下:

igetfactory get = (igetfactory)assembly.load("程序集名称").createinstance("insus.net." + mothedname + "factory");