我有一个项目的所有实体的基类,它是从下面的模型继承的:
public class BaseModel
{
public int Id { get; set; }
public int CreatedDate { get; set; }
public override string ToString();
}
现在,我有许多其他模块共有的另一种功能,我想保留该功能的BaseModel并希望从中继承它。
Public class BaseNotice
{
// Common info related to notice which is use to send notice to employees in different scenarios
}
现在我们的每个模型都假定要继承自BaseModel,因此从BaseNotice继承将是多重继承。
现在我不能喜欢以下内容:
Public class BaseNotice : BaseModel
{
// Common info related to notice which is use to send notice to employees in different scenarios
}
因为我想控制与BaseNotice模型中的Notification相关的功能,并且我想将BaseNotice保留为基本模型。
但是我在这里没有得到避免多重继承的方法,那么设计这种方法的正确方法是什么?
答案 0 :(得分:0)
不需要多重继承。您可以通过以下方式进行操作:
public class BaseModel
{
public int Id { get; set; }
public int CreatedDate { get; set; }
public override string ToString();
}
public interface IBaseNotice
{
// Base Notices Contracts should be placed here
}
Public class BaseNotice: IBaseNotice
{
// Common info related to notice which is use to send notice to employees in different scenarios
}
public class ModelX:BaseModel
{
public IBaseNotice Notice { get ; set; }
public ModelX(IBaseNotice baseNotice)
{
Notice = baseNotice;
}
}
或者您可以使用BaseModel的第二代:
public class BaseModeNoticable:BaseModel
{
public IBaseNotice Notice { get ; set; }
public BaseModeNoticable(IBaseNotice baseNotice)
{
Notice = baseNotice;
}
}