让我描述逻辑然后是类结构。有对象,所有对象必须从ConfigurationObjectBase继承。每个对象必须由Manager拥有,并且所有Manager必须从ConfigurationObjectManagerBase派生。当创建一个新的对象实例时,其中一个构造函数必须接受Manager的实例,而Manager的实例必须将该对象实例添加到名为ChildObjects的属性中。以下是课程样本。您是否可以帮助纠正以下代码中的业务规则?感谢。
public class ConfigurationObjectBase<ObjectType>
{
public ConfigurationObjectBase(ConfigurationObjectManagerBase<ObjectType> ownerManager)
{
ownerManager.ChildObjects.Add(this);
}
}
public class ConfigurationObjectManagerBase<ObjectType>
{
public ConfigurationObjectManagerBase()
{
ChildObjects = new List<ObjectType>();
}
public List<ObjectType> ChildObjects { get; set; }
}
public class Catalog : ConfigurationObjectBase<Catalog>
{
public Catalog(CatalogManager ownerManager) : base(???)
{
}
}
public class CatalogManager : ConfigurationObjectManagerBase<CatalogManager>
{
public CatalogManager() : base()
{
}
}
答案 0 :(得分:3)
您的代码中存在两个问题:
CatalogManager
应该继承自ConfigurationObjectManagerBase<Catalog>
,而不是ConfigurationObjectManagerBase<CatalogManager>
ChildObjects
应该是ConfigurationObjectBase<ObjectType>
的列表,而不是ObjectType
的列表(否则您无法为其添加ConfigurationObjectBase<ObjectType>
)所以代码应该看起来像这样:
public class ConfigurationObjectBase<ObjectType>
{
public ConfigurationObjectBase(ConfigurationObjectManagerBase<ObjectType> ownerManager)
{
ownerManager.ChildObjects.Add(this);
}
}
public class ConfigurationObjectManagerBase<ObjectType>
{
public ConfigurationObjectManagerBase()
{
ChildObjects = new List<ConfigurationObjectBase<ObjectType>>();
}
public List<ConfigurationObjectBase<ObjectType>> ChildObjects { get; set; }
}
public class Catalog : ConfigurationObjectBase<Catalog>
{
public Catalog(CatalogManager ownerManager) : base(ownerManager)
{
}
}
public class CatalogManager : ConfigurationObjectManagerBase<Catalog>
{
public CatalogManager()
{
}
}
此外,您不需要调用默认的基类构造函数(base()
),它由编译器隐式完成。