ape*_*dge 3 c# coding-style class-design class class-structure
我有这个C#类结构,我想重构使用最佳编码标准(使用接口/抽象类),因此它可以更易于维护和重用.现在的代码并不糟糕,但它并不理想.
我有一系列的TableItemGroup类:AccountTableItemGroup,PendingVoteTableItemGroup和RequestingVoteTableItemGroup.每个TableItemGrup包含一个字符串SectionName和一个List,用于其对应的TableItem ......如下:
public class AccountTableItemGroup {
public string SectionName { get; set; }
public List<AccountTableItem> Items
{
get { return this._items; }
set { this._items = value; }
}
public List<AccountTableItem> _items = new List<AccountTableItem>();
public AccountTableItemGroup()
{
}
}
Run Code Online (Sandbox Code Playgroud)
将来会有更多的TableItemGroups,除了List部分之外它们都是相同的,我不想每次都复制代码并创建一个新的Group并进行小的更改.我知道必须有更好的方法.我想继续使用List <>泛型,所以我不必在以后投出任何东西.
另一部分是TableItems.我有AccountTableItem,PendingVoteTableItem和RequestingVoteTableItem.TableItems彼此不同,但它们各自共享三个常见字符串 - TitleLabel,DetailLabel和ImageName.但在此之后,每个TableItem可能有也可能没有其他属性或方法..如下:
public class AccountTableItem
{
public string TitleLabel { get; set; }
public string DetailLabel { get; set; }
public string ImageName { get; set; }
public bool SwitchSetting { get; set; }
public AccountTableItem()
{
}
}
Run Code Online (Sandbox Code Playgroud)
所以我向大家提出的问题是,如何重新定义我的类结构以尽可能多地重用代码并使用最佳编码标准?
我在考虑使用抽象的TableItem类或使用TableItemGroup的接口?我知道使用接口或抽象类最适合编码标准,但我不知道它会如何减少我将拥有的代码量?
非常感谢您的帮助.
摘要将您的表项添加到接口或基类的必要字段:
interface ITableItem // or just a simple or abstract class
{
// common fields go here
}
Run Code Online (Sandbox Code Playgroud)
那么你可以通过约束泛型参数使你的项目组通用.
public class ItemGroup<T> where T: ITableItem
{
public string SectionName { get; set; }
public List<T> Items { get; private set; }
public ItemGroup()
{
Items = new List<T>();
}
}
Run Code Online (Sandbox Code Playgroud)