用C#中的抽象类烘干代码

时间:2015-02-22 08:51:45

标签: c# xamarin

假设我有一个带有一些“东西”的仓库,我有一些小兵在这个仓库里跑来跑去:

public class Warehouse {
    public T GetItemInfo<T>(int id) where T : IItem, new() {}

    public int AddItem<T>(T item) where T : IItem {}

    public int RemoveItem<T>(int id) where T : IItem, new() {}
}

with minion interface:

public interface IMinion<T> where T : IItem {
    T GetItemInfo(int id);
    int AddItem<T>(T item);
    int RemoveItem<T>(int id);
}

PartMinion首先出现:

public class PartMinion : IMinion<Part> {
    protected Warehouse wh;

    public PartMinion(Warehouse wh) {
        this.wh = wh;
    }

    public Parts GetItemInfo(int id) {
        return wh.GetItemInfo<Part>(id);
    }

    public int AddItem(int id) {
        return wh.AddItem<Part>(id);
    }

    public int RemoveItem(int id) {
        return wh.RemoveItem<Part>(id);
    }
}

但是,FurnitureMinionPartMinion

大致相同
public class FurnitureMinion : IMinion<Furniture> {
    protected Warehouse wh;

    public FurnitureMinion(Warehouse wh) {
        this.wh = wh;
    }

    public Furniture GetItemInfo(int id) {
        return wh.GetItemInfo<Furniture>(id);
    }

    public int AddItem(int id) {
        return wh.AddItem<Furniture>(id);
    }

    public int RemoveItem(int id) {
        return wh.RemoveItem<Furniture>(id);
    }

    private IEnumerable<Parts> GetParts(int id) {
        var query = "SELECT * FROM Parts " +
                    "JOIN FurnitureParts ON Parts.ID = FurnitureParts.PartID " +
                    "WHERE FurnitureParts.FurnitureID = ?";
        var result = wh.Query<Parts>(query, id);
        return result;
    }
}

所以我希望Abstract消除两者之间的重复代码,但我无法正确理解语法:

public abstract class AbstractMinion : IMinion<T> {
    protected Warehouse wh;

    public AbstractMinion(Warehouse wh) {
        this.wh = wh;
    }

    public Parts GetItemInfo(int id) {
        return wh.GetItemInfo<T>(id);
    }

    public int AddItem(int id) {
        return wh.AddItem<T>(id);
    }

    public int RemoveItem(int id) {
        return wh.RemoveItem<T>(id);
    }
}

1 个答案:

答案 0 :(得分:1)

尝试将通用参数添加到类中。您还需要where约束,因为此约束存在于接口IMinion上:

public abstract class AbstractMinion<T> : IMinion<T>
    where T : IItem  
{
    protected Warehouse wh;

    public AbstractMinion(Warehouse wh) {
        this.wh = wh;
    }

    public T GetItemInfo(int id) {
        return wh.GetItemInfo<T>(id);
    }

    public int AddItem(int id) {
        return wh.AddItem<T>(id);
    }

    public int RemoveItem(int id) {
        return wh.RemoveItem<T>(id);
    }
}

因此,对于PartMinion,您的课程将如下所示:

public class PartMinion : AbstractMinion<Part> {
    public PartMinion(Warehouse wh) :base(wh){
    }
}