簡體   English   中英

定義處理派生類集合的基類方法

[英]Define base class method working on derived class collection

我正在嘗試在我的基類中放置一個通用的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); }
}

代碼有效,但我不知道這個解決方案與對象有什么關系 - 是否有其他方法來定義Add方法,也許是基類中的通用方法?

使用具有基類約束的通用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); }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM