2012-01-22 36 views
3

我有一个表与一些ID,我想在default.aspx打开一个窗体,具体取决于ID的某个page.aspx。编程模式或编码风格与多个ifs /开关

我现在拥有的是:

if(id_table ==1) { 
response.redirect("PageBla.aspx"); 
} 

if(id_table==2) { 
response.redirect("Page21231.aspx"); 
} 

if(id_table==6) { 
.... 
} 
etc etc.... 

这很简单,如果我有少数ID的检查。但我会有几十个ID来检查。有没有编程模式或任何其他方法做这个没有几十ifs或switchs/case?

预先感谢

编辑: “=” 与 “==” 取代。

回答

5

这将是很容易有包含的ID和网址查找。它可能在数据库中具有灵活性,但您现在也可以将它们放入字典中,稍后添加数据库部分,如果您发现需要它。

你可以声明查找的领域:

private static readonly Dictionary<int, string> redirectLookup = new Dictionary<int,string> { 
    {1, "PageBla.aspx"}, 
    {2, "Page21231.aspx"}, 
    // ..... 
    {6, "somepage6.apx"} 

}; 

而在你的重定向逻辑:

string redirect; 
if (redirectLookup.TryGetValue(id_table, out redirect)) 
    Response.Redirect(redirect); 
else 
    // some default action when that ID was not mapped. 
+0

为什么这是downvoted? downvoting时请留言。 – driis

+0

谢谢。我认为这是最好的答案 – ajrpc

5

就创建这样的URL的简单数组:

string[] urls = {"PageBla.aspx", "Page21231.aspx"}; 
response.redirect(urls[id_table]); 

如果你有一个更复杂的使用情况下,另一种选择是使用Convention over configuration。 你可以这样做:

  1. 你的表将有字符串ID。
  2. 您重定向代码将是简单:

    Response.Redirect(tableId + ".asxp"); 
    
+0

当id_table == 3时,你的代码会发生什么?数组索引是顺序的,id_table变量不是。正如其他答案所表明的那样,使用字典是正确的解决方案。 – Abbas

+0

你为什么认为它不是顺序的?显示的代码只是一个示例代码?如果是这样,字典是一个矫枉过正。 –

+0

显示的代码显然是很不正确代表所需结果的示例代码。他没有把......放在元素2和元素6之间并不意味着他不打算这样做。正如他在'if'语句中使用'='的事实并不意味着他不是指'=='。 –

3

使用Dictionary<K,V>,而不是像,铁道部或更少,一个

var dic = new Dictionary<int, string> { {1, "PageBla.aspx"}, {2, "Page21231.aspx"}..} 

and after after cod e:

response.redirect(dic[id_table]); 
1

您可以使用Factory Design Pattern,它不会减少ifs语句,但会封装它。

更新

你可以用这种模式其他答案相结合,得到良好的书面代码

1

保持联系的Dctionary:

Dictionary<int, string> links = 
     new Dictionary<int, string>() 
    { 
     { 1, "One.aspx" }, 
     { 2, "Two.aspx" }, 
     { 3, "Three.aspx" } 
    }; 

,并使用类似:

Response.Redirect(links[id_table]); 
0

另一种选择n是将页面存储在表格中,选择要重定向到的页面。