c# - 定义处理派生类集合的基类方法

标签 c# inheritance covariance

我正在尝试在我的基类中放置一个通用的 Add 方法,该方法将适用于不同类型的类,所有类都实现了 ICollection。到目前为止一切顺利,我可以使用装箱/拆箱来实现我想要的,但我想知道是否有更好的方法来做到这一点。我很少使用协变接口(interface),但运气不佳 - 甚至可以定义 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); }
}

代码有效,但我不喜欢这种使用 object 的解决方案 - 是否有其他方法可以定义 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); }
}

关于c# - 定义处理派生类集合的基类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34986566/

相关文章:

c# - 尝试让委托(delegate)关联到控件的事件时出现问题

c# - 单击时获取 GridView 单元格的字符串值

c++ - std::find 用于继承对象 C++

scala - "return this"在返回实际类型的协变特征中

c# - 如何覆盖子类中抽象类中成员的类型

c# - 如何使用证书保护 3 跳 WCF 门面服务?

多个派生类的泛型工厂的 C# 结构

javascript - 在 JavaScript 中执行继承

c# - 如何反射(reflect)用于继承的泛型参数

python - 内置计算协方差的函数