2012-01-22 39 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是將頁面存儲在表格中,選擇要重定向到的頁面。