2011-05-29 15 views
4

這是一個後續行動這個問題How to avoid repeated code?我應該在哪裏放置一個多次調用的函數?

我使用ASP.NET 4.0 C#和我有一個名爲FillDropDownList(DropDownList ddl, DataTable dt, string dataValueField, string dataTextField, string defValue)功能被稱爲對我的ASP.NET頁面一個多次來填充一些下拉列表。我現在發現我有幾個頁面,我需要以完全相同的方式填充幾個下拉列表。

而不是在不同的頁面上覆制和粘貼相同的代碼,我應該創建一個新類並將該方法放入新類中嗎?我怎麼稱呼它?我該怎麼稱呼這個班?它應該有其他功能嗎?我在想也許我應該叫它Util?你會怎麼做?

回答

3

您可以創建靜態類,並把那裏的功能

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); 
相關問題