C# if..else语句的替代项

C# if..else语句的替代项,c#,asp.net,C#,Asp.net,我在数据库中有一个表,其中包含一组不同的控件。在我的Page_Init方法中,我需要根据传入的会话变量加载相应的控件。有没有更好的方法来实现这一点,然后使用一大堆if..else语句?我有大约15到20个不同的场景是可能的,所以我不想写20个if..else语句。非常感谢您的帮助 标题为“值”的数据表有三列:(ID、名称、说明): 这是我的代码: ControlOne c1; ControlTwo c2; ControlThree c3; protected void Page_Init(ob

我在数据库中有一个表,其中包含一组不同的控件。在我的Page_Init方法中,我需要根据传入的会话变量加载相应的控件。有没有更好的方法来实现这一点,然后使用一大堆if..else语句?我有大约15到20个不同的场景是可能的,所以我不想写20个if..else语句。非常感谢您的帮助

标题为“值”的数据表有三列:(ID、名称、说明):

这是我的代码:

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..
}

在我看来,您可以使用switch语句,只测试“Name”或“Description”

您可以这样做:

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);
}
var-controlsToLoad=new Dictionary()
{
{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(键))
{
控制c=加载控制(控制加载[键]);
面板1.控件。添加(c);
}

它比大量的if..else或switch块更紧凑、更易于阅读。

您可以使用switch语句

然而,有一个更好的方法。您的示例在DB表中有ID、名称和描述。因此,保持name字段与usercontrol名称相同,您可以执行以下操作:

string controlName = dr["Name"];
c1 = LoadControl(string.Format("~/{0}.ascx", controlName));
panel1.Controls.Add(c1);

希望这能有所帮助。

您是指switch语句吗?使用字符串到类型的映射。将字符串和Use switch case连接起来如何。是否可以向具有控件名称的表中添加另一列,然后只加载代码中动态返回的控件?请注意,您可能希望字典是一个字段,而不是本地的,只是因为没有必要在每次回发时都重新创建。非常感谢您的帮助!这是一个非常好的主意,经过深思熟虑!非常感谢你的帮助!我真的很感激!
string controlName = dr["Name"];
c1 = LoadControl(string.Format("~/{0}.ascx", controlName));
panel1.Controls.Add(c1);