假设我有一个带有一些“东西”的仓库,我有一些小兵在这个仓库里跑来跑去:
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);
}
}
但是,FurnitureMinion
与PartMinion
:
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);
}
}
答案 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){
}
}