我应该在哪里放置一个多次调用的函数?

问题描述:

这是一个后续行动这个问题How to avoid repeated code?我应该在哪里放置一个多次调用的函数?

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

而不是在不同的页面上复制和粘贴相同的代码,我应该创建一个新类并将该方法放入新类中吗?我怎么称呼它?我该怎么称呼这个班?它应该有其他功能吗?我在想也许我应该叫它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);