我需要在子母关系中继承和抽象两个层次 [英] I need to 2 levels of inheritance and abstraction in master-child relationship
问题描述
假设我有一个业务案例,我想使用某种模型来表示主子结构.而且某些类可以同时从主类和子类中继承.
Let's assume I have a business case I want to use some model to represent a master-child structure. And there will be certain classes to inherit from both the master class and child class.
我使用下面的示例
public abstract class BaseChild
{
public int MyProperty { get; set; }
}
public abstract class BaseMaster
{
public abstract ReadOnlyCollection<BaseChild> Children { get; }
}
现在,我需要真实的类来继承它们.因此,有
Now I need real classes to inherit from them. So have following
public class FirstRealChild : BaseChild
{
public int AdditionalProperty { get; set; }
}
public class FirstRealMaster : BaseMaster
{
public ReadOnlyCollection<FirstRealChild> Children { get; }
}
当然会因为错误而无法编译
Of course it won't compile because of the error
'FirstRealMaster'未实现继承的抽象成员 'BaseMaster.Children.get'
'FirstRealMaster' does not implement inherited abstract member 'BaseMaster.Children.get'
我可以从BaseMaster
类中删除public abstract ReadOnlyCollection<BaseChild> Children { get; }
,但是它对所有需要子类的继承类都失去了约束.
I can remove the public abstract ReadOnlyCollection<BaseChild> Children { get; }
from BaseMaster
class, but it loses the constraint to all inherited classes that children are required.
有人有更好的主意吗?
推荐答案
您可能会使用泛型:
public abstract class BaseMaster<TChild> where TCHild : BaseChild
{
// this probably doesn't have to be 'abstract' anymore
public abstract ReadOnlyCollection<TChild> Children { get; }
}
public class FirstRealMaster : BaseMaster<FirstRealChild>
{
}
但是,我们对Master和Child类之间的关系了解得还不够清楚.
But we don't know enough about the relation between Master and Child classes to be sure.
这篇关于我需要在子母关系中继承和抽象两个层次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!