c# - 我应该把一个被多次调用的函数放在哪里?

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

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

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

与其在不同的页面中复制和粘贴相同的代码,不如创建一个新类并将方法放入该新类中?我怎么调用它?我应该怎么称呼这个类(class)?它应该有其他功能吗?我在想也许我应该称它为 Util?你会怎么做?

最佳答案

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

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

关于c# - 我应该把一个被多次调用的函数放在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6168601/

相关文章:

c# - 如何强制 Asp.net 开发服务器作为 32 位进程运行?

c# - 将资源转换为 byte[]

asp.net - 测试以确定您的开发环境?

c#-4.0 - 访问修改后的闭包 - ref int

c# - 难以在 C# 中的 SQLite 数据库上运行并发 INSERTS

c# - 如何保护将重要数据发布到我的数据库的公共(public) ASMX 页面

c# - 在 Azure 上的 ASP.NET 中缓存 WCF ChannelFactory 或客户端代理?

c# - 在后面创建数据模板代码

wpf - C#如何获取不同国家的当前时间

c# - 有没有一种方便的方法可以将所有接口(interface)方法映射到一个子对象上?