【发布时间】:2011-04-03 16:54:47
【问题描述】:
我想让这个方法称为 RegisterCollection,目的是在 DomainObject 中注册子对象的集合。这个想法是我想在一个列表中注册集合,这样当我在我的 DomainObject 上调用 Save() 时,它会在每个注册的集合子域对象上调用 save。
我已编写此代码,但在构建时出现此错误:参数类型“OrderCollection”不可分配给参数类型集合。
我在 .Net 3.5 中使用 C#。我在某处读到.NET 4.0 支持失败的转换类型。不确定这是否被正确理解,但无论如何,我希望有人对其他方法或解决方法提出一些建议。
这可能通过某种命令模式实现吗?
public interface IDomainObject
{
void Save();
}
public class DomainObject : IDomainObject
{
private readonly IList<Collection<IDomainObject>> m_Collections = new List<Collection<IDomainObject>>();
protected void RegisterCollection(Collection<IDomainObject> collection)
{
m_Collections.Add(collection);
}
/// <summary>
/// Saves this instance collections.
/// </summary>
public virtual void Save()
{
SaveCollections();
}
private void SaveCollections()
{
foreach (var itemCollection in m_Collections)
{
foreach (var item in itemCollection)
{
item.Save();
}
}
}
}
public class OrderCollection : Collection<IOrder>
{
}
public interface IOrder : IDomainObject
{
}
public class Customer : DomainObject
{
private readonly OrderCollection m_OrderCollection = new OrderCollection();
public Customer()
{
// Throws: Argument type 'OrderCollection' is not assignable to parameter type Collection<IDomainObject>
RegisterCollection(m_OrderCollection);
}
}
【问题讨论】:
标签: c# .net design-patterns generics collections