c# - 将接口(interface)成员定义为类或其接口(interface)等效项是更好的做法吗?

标签 c# .net

在接口(interface)定义中,声明所需类或接口(interface)等效类型的成员是否更好?例如,假设我们有一个名为 IFoo 的接口(interface)由类 Foo 实现。如果我们声明另一个接口(interface)IBar ,我们需要 IBar 中 *Foo 事物的表示哪个更好?

interface IBar { 
    IFoo member { get; set; }  // interface
}

或者...

interface IBar { 
    Foo member { get; set; }   // class
}

两个阵营似乎都有同样有效的论点。你有什么想法?

最佳答案

使用接口(interface)可以更轻松地将初始实现替换为新实现,而无需更新引用,因为它们处理接口(interface)提供的抽象。 它还可以帮助您进行单元测试,因为您可以轻松地基于接口(interface)进行模拟。

一个常见的例子是 IList,如果使用接口(interface),您的代码会更加灵活。

关于c# - 将接口(interface)成员定义为类或其接口(interface)等效项是更好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27054667/

相关文章:

.net - application/problem+json 和 .net 6 最小 API?

c# - 如何确定云WebRole在硬盘上的位置?

.NET OpenId 库 - 提供者和消费者

php - 检查在 mysql startdate enddate 列之间找到的日期 renge

c# - 如何使用 C# 在 Windows CE 中将 SQL Server Compact 表导出到 Excel?

C# 扩展类在 Visual Studio 2013 中不起作用,在 2015 中起作用

c# - p/invoke 不平衡堆栈错误

c# - 配置与静态属性、安全问题

c# - 编译错误。将属性与结构一起使用

c# - where 条件下的动态列