if..else语句的替代方案

Tim*_*eid 2 c# asp.net

我在数据库中有一个表,其中包含一堆不同的控件.在我的Page_Init方法中,我需要根据传入的Session变量加载适当的控件.有没有更好的方法来执行此操作然后使用一大堆if..else语句?我有大约15到20种不同的场景,所以我不想写20个if..else语句.任何帮助是极大的赞赏!

名为"Value"的DataTable有三列:(ID,Name,Description):

ID | Name | Description
-------------------
 1 | A    | First   
 2 | B    | Second   
 3 | C    | Third       
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

ControlOne c1;
ControlTwo c2;
ControlThree c3;

protected void Page_Init(object sender, EventArgs e)
{
    DataSet DS = Client.GetInformation(Session["Number"].ToString());
    DataRow DR = DS.Tables["Value"].Rows[0];

    if (DR["Name"].ToString() == "A" && DR["Description"].ToString() == "First")
    {
        c1 = (ControlOne)LoadControl("~/ControlOne.ascx");
        panel1.Controls.Add(c1);
    }
    else if (DR["Name"].ToString() == "B" && DR["Description"].ToString() == "Second")
    {
        c2 = (ControlTwo)LoadControl("~/ControlTwo.ascx");
        panel1.Controls.Add(c2);
    }
    else if (DR["Name"].ToString() == "C" && DR["Description"].ToString() == "Third")
    {
        c3 = (ControlThree)LoadControl("~/ControlThree.ascx");
        panel1.Controls.Add(c3);
    }
    else if... //lists more scenarios here..
}
Run Code Online (Sandbox Code Playgroud)

p.s*_*w.g 7

你可以这样做:

var controlsToLoad = new Dictionary<Tuple<string, string>, string>()
{
    { Tuple.Create("A", "First"), "~/ControlOne.ascx" },
    { Tuple.Create("B", "Second"), "~/ControlTwo.ascx" },
    { Tuple.Create("C", "Third"), "~/ControlThree.ascx" },
    ... 
};

var key = Tuple.Create(DR["Name"].ToString(), DR["Description"].ToString());
if (controlsToLoad.ContainsKey(key))
{
    Control c = LoadControl(controlsToLoad[key]);
    panel1.Controls.Add(c);
}
Run Code Online (Sandbox Code Playgroud)

它比一个巨大的if..else或开关块更紧凑,更容易阅读.

  • 请注意,您可能希望字典是一个字段而不是本地字典,因为不需要在每个回发上重新创建它. (4认同)