有人可以告诉我如何以更好,更优雅的方式重写下面的方法吗?
// in class------------------
public static void RefreshAllDropdownlists(DropDownList ddlRemoveUsersFromRole, DropDownList ddlAddUsersToRole, DropDownList ddlAddAllUsersToRole, DropDownList ddlRemoveAllUsersFromRole, DropDownList ddlDeleteAllUsersFromRole)
{
ddlRemoveUsersFromRole.ClearSelection();
ddlAddUsersToRole.ClearSelection();
ddlAddAllUsersToRole.ClearSelection();
ddlRemoveAllUsersFromRole.ClearSelection();
ddlDeleteAllUsersFromRole.ClearSelection();
}
// in codebehind------------------
UserGvUtil.RefreshAllDropdownlists(ddlRemoveUsersFromRole, ddlAddUsersToRole, ddlAddAllUsersToRole, ddlRemoveAllUsersFromRole, ddlDeleteAllUsersFromRole);
谢谢!
答案 0 :(得分:7)
使用params
参数修饰符传递DropDownList
s:
public static void RefreshAllDropdownlists(params DropDownList[] dropDownLists)
{
foreach (DropDownList ddl in dropDownLists)
{
ddl.ClearSelection();
}
}
用法与您当前的方法相同
答案 1 :(得分:2)
var listsToRefresh = new List<DropDownList>
{
ddlRemoveUsersFromRole,
ddlAddUsersToRole,
ddlAddAllUsersToRole,
ddlRemoveAllUsersFromRole,
ddlDeleteAllUsersFromRole
};
listsToRefresh.ForEach(l=>l.ClearSelection());
有很多方法可以做到这一点,我更喜欢这个。如果你所做的只是在每一个上执行ClearSelection(),那么就不需要为那一行代码创建一个方法。但是,如果你想在每个DropDownlist上做更多的工作,那么我认为使用扩展方法可以保持优雅。
public static class DropDownListExtensions
{
public static void Reset(this DropDownList dropDownList)
{
dropDownList.ClearSelection();
//... do more stuff
}
}
listsToRefresh.ForEach(l=>l.Reset());
答案 2 :(得分:1)
像
这样的东西public static void RefreshAllDropdownlists(params DropDownList[] dropDownLists)
{
if (dropDownLists != null)
foreach (var ddl in dropDownLists)
ddl.ClearSelection();
}
答案 3 :(得分:1)
您可以将DropDownList对象列表传递给该函数,然后您可以执行:
public static void RefreshAllDropdownlists(List<DropDownList> lists)
{
foreach(DropDownList dropDown in lists)
{
dropDown.ClearSelection();
}
}