我有兩個類從CheckBoxList派生和第二個從DropDownList。裏面的代碼是完全一樣的。唯一的區別是我需要第一個顯示checkboxlist的地方,第二個顯示dropdownlist。下面是我的代碼:如何使共同的子類刪除重複的代碼
using System;
using System.Collections.ObjectModel;
using System.Web.UI.WebControls;
namespace Sample
{
public class MyCheckBoxList : CheckBoxList
{
public int A { get; set; }
public int B { get; set; }
protected override void OnLoad(EventArgs e)
{
//dummy task
Collection<int> ints = new Collection<int>();
//........
this.DataSource = ints;
this.DataBind();
}
}
}
第二個
using System;
using System.Collections.ObjectModel;
using System.Web.UI.WebControls;
namespace Sample
{
public class MyDropDownList : DropDownList
{
public int A { get; set; }
public int B { get; set; }
protected override void OnLoad(EventArgs e)
{
//dummy task
Collection<int> ints = new Collection<int>();
//........
this.DataSource = ints;
this.DataBind();
}
}
}
現在你可以看到內部的代碼正好是我想要避免一樣。我如何爲它創建一個通用的類來消除代碼重複?
+1努力減少代碼冗餘。雖然你的問題可能更適合這裏:http://codereview.stackexchange.com/ –
@KileyNaro:很酷的瞭解codereview,不知道它存在。不要認爲它與SO不匹配。我認爲很好的問題。 +1 –