2013-03-27 99 views
3

我有两个图形对象(说某种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; 
} 

这是短,任何潜在的额外表是很简单。它有什么缺点吗?

+0

这就是它。重复的代码和多个'if'语句是一种常见的代码异味。 – Groo 2013-03-27 14:20:20

+0

你的第二种方法可能有点聪明。而不是接受一个'int tableIndex'作为参数,你可以改用'Table table'。 'void FormatTable(Table table)'。这样你就不需要'if',你的代码变得更短,更容易阅读。 – Nolonar 2013-03-27 14:25:06

+0

您也可以考虑将列表作为父类的私有字段,其中包含所有表(以避免在您要将操作应用于所有表时必须重新创建列表)。 – Groo 2013-03-27 14:34:29

回答

7

没有跳出作为错误,但我会按照你原来的想法去实际上把它放在一个方法中,而不是传入实际的表中。

public void Format(Table table) 
{ 
    table.BorderWidth = 2; 
    table.BorderColor = Color.GloriousPink; 
} 

foreach(Table table in tables) 
{ 
    Format(table); 
} 
2

我不知道你的要求,但如何对一些功能性的风格:

Action<Table> formatTable = (table) => { 
    table.BorderWidth = 2; 
    table.BorderColor = Color.GloriousPink; 
}; 

new List<Table> { table1, table2 }.ForEach(formatTable); 

如果你不喜欢这些东西Action

void FormatTable(Table table) 
{ 
    table.BorderWidth = 2; 
    table.BorderColor = Color.GloriousPink; 
} 

new List<Table>{ table1, table2 }.ForEach(FormatTable); 
+0

对于这样一个简单的操作,这可能是一个矫枉过正的情况,除非应用函数在运行时需要互换。 – Groo 2013-03-27 14:22:31

+0

想法是,他可以拥有'ApplyTable'类的成员并将其传递给ForEach' – 2013-03-27 14:23:19

+0

他确实说这是一个非常简单的示例,并且可能会增长... – 2013-03-27 14:26:20

2

让编译器创建数组:

void FormatTable(params Table[] tables) 
{ 
    foreach(var table in tables) 
    { 
     table.BorderWidth = 2; 
     table.BorderColor = Color.GloriousPink; 
    } 
} 

,并调用它像这样:

FormatTables(table1, table2); 
+0

使用'params'的+1 – Nolonar 2013-03-27 14:28:26

相关问题