如何消除接口之间的重复

本文关键字:之间 接口 何消 | 更新日期: 2023-09-27 18:23:59

我有一组正在使用的接口。他们是IPpatient、IDoctor和IPerson。IPerson包含每个人的共享属性(姓名、性别、地址等)。我希望IDoctor和IPpatient实现IPerson,但根据这个问题,这不能在C#中完成。。

有什么方法可以消除IPpatient和IDoctor之间的这些重复属性吗?

如何消除接口之间的重复

您所说的重复在哪里?如果你看一个例子:

interface IPerson
{
    string Name { get; set; }
}
interface IDoctor : IPerson
{
    string Specialty {get; set; }
}
class Doctor : IDoctor
{
   public string Name { get; set; }
   public string Specialty {get; set;}
}

这里没有重复-Doctor只需要实现一次Name属性,当然也必须实现Specialty属性。

接口只提供了一个接口,而不是属性的实现(在大多数情况下,这正是你想要利用多态性的原因)-如果你需要这些属性的默认实现,你可能应该使用一个实现这些属性的抽象基类。

这绝对是可能的。链接问题还有一个约束,即没有其他类可以实现接口。我们可以简单地消除这种无稽之谈的限制:

interface IPerson
{   
    string Name { get; }
}
interface IDoctor: IPerson
{
    int DoctorSpecificProperty { get; }
}
interface IPatient
{
    int PatientSpecificProperty { get; }
}

如您提供的链接所示,IPient和IDoctor都可以扩展IPerson,只是在不实现IPient或IDoctor的情况下无法阻止某人实现IPerson。