接口实现成员可否为接口成员的派生类?C#场景问询
能否在无显式实现的前提下让Model类实现IListInterface?
问题背景
给定如下接口:
interface IListInterface { IList<int> List { get; } }
现有Model类包含ObservableItemCollection<int>类型的List属性,且ObservableItemCollection<int>在继承链中实现了IList<int>:
class Model { ObservableItemCollection<int> List { get; } }
想问是否可以不添加显式实现,直接让Model实现IListInterface,即如下代码能否编译通过:
class Model : IListInterface { ObservableItemCollection<int> List { get; } }
结论:可以
这种场景下无需显式实现,代码就能正常编译,Model类会自动满足IListInterface的接口要求。
原因说明
C#允许在实现接口的只读属性时使用协变返回类型:
- 接口定义的属性返回抽象的
IList<int>接口类型 - 实现类的同名只读属性返回具体的
ObservableItemCollection<int>类型,而该类型是IList<int>的实现类 - 只读属性的
get操作属于输出位置,协变规则允许用更具体的类型替代抽象接口类型,编译器会自动识别该属性作为接口属性的实现。
注意事项
如果接口中的属性包含set访问器(即可写属性),这种写法就无法生效:
// 带可写属性的接口示例 interface IListInterface { IList<int> List { get; set; } }
此时Model的ObservableItemCollection<int> List无法隐式实现接口,因为set操作需要接受任意IList<int>类型的实例,而ObservableItemCollection<int>是更具体的类型,编译器无法保证类型安全,这种情况必须显式实现接口或者修改属性类型。
内容的提问来源于stack exchange,提问作者Timofeus
相关产品推荐
相关产品推荐

