接口隔离原则下多接口继承重复父字段问题的解决方案咨询
前置说明
你感知到的「重复继承字段/方法」问题绝大多数场景下是无实际影响的伪问题:
- TypeScript 中接口多继承时,相同名称、相同类型的字段会自动合并,不会产生类型冲突
- C# 中同源的接口方法继承只会要求你实现一次,运行时不会存在重复的方法声明
如果需要从设计层面彻底消除冗余感知,可以用以下方案调整结构:
TypeScript 优化方案
调整继承层级,将独立的行为接口和身份基接口拆分,仅在最终业务类型处合并:
// 基础身份类型保持不变 type Person = { name: string; age: number; }; // 行为接口不再直接继承Person interface Employee { salary: number; } interface Director { sharesHeld: number; } // 最终业务类型一次性继承所有需要的接口,仅继承一次Person interface CompanyFounder extends Person, Director, Employee { getReasonStartedCompany: string; } interface NonExecDirector extends Person, Director { // 注:你原代码中此处属性名和类型写反了,修正为如下写法 getExternalStuff: string[]; }
如果业务逻辑要求Employee/Director本身必须是Person的子类型,可以改用交叉类型定义,同样不会产生重复继承问题:
type Employee = Person & { salary: number } type Director = Person & { sharesHeld: number }
C# 优化方案
和TS思路一致,拆分接口层级即可:
// 基础身份接口 public interface IPerson { string GetName(); int GetAge(); } // 行为接口不继承基础身份接口 public interface IEmployee { int GetSalary(); } public interface IDirector { int GetSharesHeld(); } // 最终业务接口一次性合并,仅继承一次IPerson public interface ICompanyFounder : IPerson, IDirector, IEmployee { string GetReasonStartedCompany(); } public interface INonExecDirector : IPerson, IDirector { string[] GetExternalStuff(); }
如果业务必须要求IEmployee/IDirector继承IPerson,也不需要额外处理:C#编译器会自动识别同源的接口方法,你只需要实现一次GetName和GetAge即可,不需要重复实现,也不会有运行时冲突。
内容的提问来源于stack exchange,提问作者Andy
相关产品推荐
相关产品推荐

