减少具有不同嵌套类的两个类中的代码重复

chi*_*s42 4 c# enums refactoring xml-serialization

我有两个类(这是C#)非常相似,除了它们各自包含自己的嵌套类和枚举.

我想重构它们都从一个抽象类继承,但我遇到了一个问题,因为这些方法都与嵌套类类型紧密耦合.

我的第一个计划是拉出ItemDetails类,但它链接到ItemType,这是一个特定于每个视图项类的枚举.此外,我不能只使用System.Enum作为类型,因为我需要能够将详细信息序列化到xml文件.

我怎样才能减少这些课程中的重复?

public class FirstViewItem
{
    [Serializable]
    public class ItemDetails
    {
        public ItemType Type;
        public int Width;
        public string Text;
        public int DisplayOrder;
    }

    public enum ItemType
    {
        None = 0,
        A,
        B,
        C
    }

    public FirstViewItem()
    {
        // ...
    }

    public List<ItemDetails>()
    {
        // code here ...
    }
}

public class SecondViewItem
{
    [Serializable]
    public class ItemDetails
    {
        public ItemType Type;
        public int Width;
        public string Text;
        public int DisplayOrder;
    }

    public enum ItemType
    {
        None = 0,
        X,
        Y,
        X
    }

    public SecondViewItem()
    {
        // ...
    }

    public List<ItemDetails>()
    {
        // code here ...
    }
}
Run Code Online (Sandbox Code Playgroud)

yam*_*men 5

您希望创建一个依赖于传入的项类型枚举的泛型类:

public class ViewItem<T>
{
    [Serializable]
    public class ItemDetails
    {
        public T Type; // the generic type is inserted here
        public int Width;
        public string Text;
        public int DisplayOrder;
    }

    // common code that uses ItemDetails
}
Run Code Online (Sandbox Code Playgroud)

然后是一些项目类型:

public enum FirstItemType
{
    None = 0,
    A,
    B,
    C
}

public enum SecondItemType
{
    None = 0,
    X,
    Y,
    Z
}
Run Code Online (Sandbox Code Playgroud)

然后用法:

var firstViewItem = new ViewItem<FirstItemType>();
Run Code Online (Sandbox Code Playgroud)