3

我有两个图形对象(比如某种Tables),我想设置它们的样式。简单的代码如下:

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

这更短,并且任何潜在的附加表都非常简单地添加。它有什么缺点吗?

4

3 回答 3

7

没有什么是错误的,但我会按照你最初的想法去做,实际上把它放在一个方法中,而不是传入实际的表。

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

foreach(Table table in tables) 
{
   Format(table);
}
于 2013-03-27T14:20:51.530 回答
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);
于 2013-03-27T14:19:28.937 回答
2

让编译器创建数组:

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

并这样称呼它:

FormatTables( table1, table2);
于 2013-03-27T14:27:47.937 回答