gpt4 book ai didi

c# - 如何制作一个公共(public)子类来删除重复代码

转载 作者:太空狗 更新时间:2023-10-29 23:33:56 28 4
gpt4 key购买 nike

我有两个类,一个派生自 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();
}
}
}

现在您可以看到内部代码与我想要避免的完全相同。如何为它创建一个通用类以消除代码重复?

最佳答案

你可以创建第三个类

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

然后在其他类中使用它

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

关于c# - 如何制作一个公共(public)子类来删除重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7590034/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com