【问题标题】:Where should I put a function that is called many times?我应该把一个被多次调用的函数放在哪里?
【发布时间】:2011-09-04 08:17:53
【问题描述】:

这是这个问题的后续How to avoid repeated code?

我正在使用带有 C# 的 ASP.NET 4.0,并且我有一个名为 FillDropDownList(DropDownList ddl, DataTable dt, string dataValueField, string dataTextField, string defValue) 的函数,它在我的一个 ASP.NET 页面上被多次调用以填充一些下拉列表。我现在发现我有几个页面需要以完全相同的方式填充几个下拉列表。

我应该创建一个新类并将方法放入该新类中,而不是在不同页面中复制和粘贴相同的代码吗?我该怎么称呼它?我应该怎样称呼班级?它应该有其他功能吗?我在想也许我应该叫它Util?你会怎么做?

【问题讨论】:

    标签: c# asp.net c#-4.0 refactoring


    【解决方案1】:

    你可以创建静态类并将你的函数放在那里

    public static class DropDownFiller
    {
       public static void  FillDropDownList(DropDownList ddl, DataTable dt, string dataValueField, string dataTextField, string defValue)
       {
            /// bla bla
       }
    }
    

    或者你可以创建一个 DropDownList 的扩展(它也是一个静态类)

    public static class DropDownListExtension
    {
       public static void  FillDropDownList(this DropDownList ddl, DataTable dt, string dataValueField, string dataTextField, string defValue)
       {
            /// bla bla
       }
    }
    

    用法(类似DropDownList的方法)

    yourDropDownList.FillDropDownList(dataTable,valueField,textField,defValue);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-30
      • 2016-08-25
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-28
      相关资源
      最近更新 更多