我试图在我的基类中放置一个通用的 Add 方法,该方法适用于不同类型的类,所有类都实现 ICollection 。到目前为止这么好,我能够使用装箱/拆箱来实现我想要的,但我想知道是否有更好的方法来做到这一点。我对协变界面玩的很少,但没有更好的运气 - 甚至可以定义 IVariantCollection 吗?
这里有一些代码可以解释我尝试实现的目标:
public abstract class Device
{
public string Name { get; set; }
public abstract void Print();
}
public class Printer : Device { public override void Print() => Debug.WriteLine($"{Name} printer printout"); }
public class Xero : Device { public override void Print() => Debug.WriteLine($"{Name} xero printout."); }
public abstract class Factory
{
public abstract IEnumerable<Device> DeviceCollection { get; }
public abstract void Add(object added);
public void ListDevices() { foreach (var item in DeviceCollection) Debug.WriteLine($"Device: {item.Name}"); }
}
public class PrinterFactory : Factory
{
public List<Printer> Printers = new List<Printer>();
public override IEnumerable<Device> DeviceCollection => Printers;
public override void Add(object added) { Printers.Add((Printer)added); }
}
public class XeroFactory : Factory
{
public ObservableCollection<Xero> Xeros = new ObservableCollection<Xero>();
public override IEnumerable<Device> DeviceCollection => Xeros;
public XeroFactory() { Xeros.CollectionChanged += (s, e) => Debug.WriteLine($"Device added: {e.NewItems[0]}"); }
public override void Add(object added) { Xeros.Add((Xero)added); }
}
代码有效,但我不知道这个解决方案与对象 - 还有其他方法来定义添加方法,也许是基础上的通用方法类?
答案 0 :(得分:3)
将通用Factory
与基类约束
public abstract class Factory<TDevice> where TDevice : Device
{
public abstract IEnumerable<TDevice> DeviceCollection { get; }
public abstract void Add(TDevice added);
public void ListDevices()
{
foreach (var item in DeviceCollection)
Debug.WriteLine($"Device: {item.Name}");
}
}
然后
public class PrinterFactory : Factory<Printer>
{
public List<Printer> Printers = new List<Printer>();
public override IEnumerable<Printer> DeviceCollection => Printers;
public override void Add(Printer added) { Printers.Add(added); }
}