6

I have a method with the following signature:

string GetTableCellValue(DataTable table, string columnName, int rowIndex){}

As you might guess, this method returns the value of the cell located at the specified column of the specified row of the specifies table in string format. It turns out that I need this methods almost in all the webpages. Here's my quetion(s):

  1. Should I put this method in all the code files or?
  2. Should I have it as a static method of some class, like Utilities_Class or?
  3. Should I have it as a public NON-STATIC method of some class , like Utilities_Class?

The last 2 choices seem to be better idea. But I don't know which one to choose eventually.

4

4 回答 4

10

您可能想为此创建一个静态方法。具体来说,扩展方法

public static class Extensions
{
    public static string GetTableCellValue(this DataTable table,
                                           string columnName, int rowIndex)
    {
        // ...
    }
}

现在,您可以像在DataTable对象上调用实例方法一样调用它:

DataTable dataTable = ...;
var value = dataTable.GetTableCellValue("column", row);
于 2013-02-05T13:38:40.157 回答
2

我会选择第二个选项,因为我不需要类的实例,例如 Utilities_Class。GetTableCellValue 与它的数据成员或方法无关,使其成为静态是相当合理的。使其扩展方法来调用它,就像它存在于 DataTable 类中一样。

public static class DataExtensions
{
    public static string GetTableCellValue(this DataTable table, string columnName, int rowIndex)
    {
        // implementation
    }
}
于 2013-02-05T13:38:45.303 回答
1

您还可以将其创建为扩展方法,例如:

public static class DataExtensions
{
    public static string GetTableCellValue(this DataTable table, string columnName, int rowIndex)
    {
        // implementation
    }
}
于 2013-02-05T13:38:54.433 回答
0

这些都没有。

我建议您定义自己的 Page(我们称之为 BasePage)继承自 Page,并在 BasePage 中添加方法。

您的每个页面都应该是 BasePage 的实例,而不是常规 Page。

编辑:正如 Daniel Hilgarth 指出的那样,扩展是比我建议的更好的选择。请保留此帖子,以便其他人了解不该做什么:)

于 2013-02-05T13:40:21.053 回答