如何在条件语句中重构相似的代码?

时间:2018-12-12 09:06:53

标签: c#

我想重构这段big肿的代码,我觉得有更好的方法来重写它。有人知道怎么做吗?

if (ls.SelectedIndex == 1) { grid1.Visibility = Visibility.Visible; }
...
if (ls.SelectedIndex == 58) { grid58.Visibility = Visibility.Visible; }

1 个答案:

答案 0 :(得分:1)

创建网格数组

var gridArray = new Grid[N];

填写:

gridArray[1] = grid1;
gridArray[2] = grid2;
...

使用:

gridArray[ls.SelectedIndex].Visibility = Visibility.Visible;