定义接口类型变量而不是派生类类型的目的是什么?
我将在此示例中解释我的问题:
ICollection<Employee> listOfEmployee = new List<Employee>();
//listOfEmployee = Some code;
在c#,列表中&lt; t&gt;
从ilist&lt; t&gt; t&gt; t&lt; t&gt; t&gt; t&gt; t&gt; t&gt; ;因此,这意味着
list&lt; t&gt;
具有这些Intercafes具有的所有方法。
在上面的此示例中,为什么我们有时会使用
Icollection&lt;雇员&gt; ListOfemployee =新列表&lt;雇员&gt;();
或
iEnumerable&lt; employee&gt; ListOfemployee =新列表&lt;雇员&gt;();
等...而不是吗
List<Employee> listOfEmployee = new List<Employee>();
?有任何性能好处吗?
I will explain my issue with this example:
ICollection<Employee> listOfEmployee = new List<Employee>();
//listOfEmployee = Some code;
In C#, List<T>
inherits from IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>
interfaces. So this means List<T>
have all methods that these intercafes have.
In this example above why do we sometimes use
ICollection<Employee> listOfEmployee = new List<Employee>();
or
IEnumerable<Employee> listOfEmployee = new List<Employee>();
etc... instead of
List<Employee> listOfEmployee = new List<Employee>();
this? Is there any performance benefits or something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常,最好使用最简单的类型。从长远来看,如果您决定以后更改较高级别的类型,则它更加灵活。例如,这无需更改代码:
如果您使用最高级别类,例如第二个示例:
即使您仅使用Icollection&lt;&gt;&gt;界面。由于您不需要访问列表中获得的所有高级功能,因此使用Icollection&gt;。
编辑:这也是指示您计划使用哪些操作的一种好方法。如果您只打算在列表中迭代,那么也许是可以走的路。但是,如果您想以后添加和插入对象,那么您可以在那里使用列表
In general, it's good practice to use the simplest type you need. It's more flexible in the long run if you decide to change the higher level type later on. For example, this works with no changes to your code:
If you were to use the highest level class like your second example instead:
This would throw a compile-time error, even though you're only using methods from the ICollection<> interface. Since you don't need to access all of the higher-level functionality you get in a List<>, it's more maintainable this way to use ICollection<>.
Edit: It's also a good way to indicate what type of operations you plan on using with your object. If you only intend to iterate through the list, then maybe IEnumerable is the way to go. But if you want to add and insert objects later on, then you might use a List there instead
我建议您阅读为什么我们使用Interfaces v。混凝土类型。在您的示例中,接口传达了消费者在收藏中可以做的操作类型。
iEnumerable
指出只能迭代项目,其中Icollection
允许在集合中插入和删除项目。I would recommend you read up on why we use interfaces v. concrete types. In your examples, the interfaces convey, among other things, the type of operations a consumer can do on a collection.
IEnumerable
indicates items can only be iterated, where asICollection
allows for inserting and removing items in the collection.