Roc*_*ngh 5 c# asp.net oop design-patterns
我有两个类,一个是从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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
第二个
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在您可以看到内部代码完全相同,我想避免.如何为它创建一个公共类以删除代码重复?
您可以创建第三个类
public class Entity
{
public int A { get; set; }
public int B { get; set; }
Collection<int> GetCollection()
{
//dummy task
Collection<int> ints = new Collection<int>();
//........
return ints;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在其他类中使用
public class MyDropDownList : DropDownList
{
public MyDropDownList() { Entity = new Entity(); }
public Entity {get;set;}
protected override void OnLoad(EventArgs e)
{
this.DataSource = Entity.GetCollection();
this.DataBind();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
873 次 |
| 最近记录: |