我有两个图形对象(说某种Table
s),我想设置它们的样式。琐碎代码如下:(真正的代码有更多行)对同一类型的多个对象执行大量操作
table1.BorderWidth = 2;
table1.BorderColor = Color.GloriousPink;
table2.BorderWidth = 2;
table2.BorderColor = Color.GloriousPink;
更巧妙的方式,使用的方法。
void Format Table(int tableIndex)
{
Table table;
if(tableIndex == 1)
table = table1;
if(tableIndex == 2)
table = table2;
table.BorderWidth = 2;
table.BorderColor = Color.GloriousPink;
}
我想了一个办法,使之更具可扩展性(在if
/switch
部分生长快),我想出了:
foreach(Table table in new List<Table> { table1, table2 })
{
table.BorderWidth = 2;
table.BorderColor = Color.GloriousPink;
}
这是短,任何潜在的额外表是很简单。它有什么缺点吗?
这就是它。重复的代码和多个'if'语句是一种常见的代码异味。 – Groo 2013-03-27 14:20:20
你的第二种方法可能有点聪明。而不是接受一个'int tableIndex'作为参数,你可以改用'Table table'。 'void FormatTable(Table table)'。这样你就不需要'if',你的代码变得更短,更容易阅读。 – Nolonar 2013-03-27 14:25:06
您也可以考虑将列表作为父类的私有字段,其中包含所有表(以避免在您要将操作应用于所有表时必须重新创建列表)。 – Groo 2013-03-27 14:34:29