差异b / w通过IList和List创建实例 [英] Difference b/w creating the instance over IList and List

查看:95
本文介绍了差异b / w通过IList和List创建实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

差异b / w在IList和List上创建实例



Ex ::



Difference b/w creating the instance over IList and List

Ex ::

IList<Customer> objIlistCust = new List<Customer>();  
List<Customer> objListCustomer = new List<Customer>();

推荐答案

创建的实例没有区别 - 这是右侧的等于 - 左边的变量是不同的。因为变量是对接口而不是具体类的引用,所以您只能编译使用接口属性,方法和字段的语句 - 您不能使用特定于List< T>的任何方法。尽管实例,该变量实际上是指具体的List< T>。对象。

这是因为就编译器而言,变量可能包含任何实现IList接口的类,并不是所有类都是List类实例。



这就像说汽车是车辆:

There is no difference in the created instance - that is the right hand side of the equals - it's the variable on the left that is different. Because the variable is reference to the interface rather than the concrete class, you can only compile statements that use the interface properties, methods, and fields - you cannot use any methods with are specific to the List<T> class despite the instance the variable actually refers to being a concrete List<T> object.
This is because as far as the compiler is concerned, the variable may contain any class that implements the IList interface, and not all of them will be List class instances.

It's like saying a Car is a Vehicle:
Vehicle v = new Car("Ford", "Mustang");

下次使用Vehicle时,你甚至无法依赖车轮的数量,因为我可以还说:

When you use the Vehicle next time, you can't even depend on the number of wheels, because I could also say:

v = new Motorcycle("Yamaha", "R1");



如果我说:


If I say:

Car c = new Car("Ford", "Fiesta");

然后我可以取决于轮数,因为如果我试着说,编译器会抱怨:

Then I can depend on the wheel count, because the compiler will complain if I try to say:

c = new Motorcycle("Honda", "Fireblade");

因为 知道 摩托车不是汽车。

Because it knows that a Motorcycle is not a Car.


Lee的好解释



我遵循两条规则:



接受最基本的工作类型

返回用户需要的最丰富的类型



因此,在编写采集集合的函数或方法时,不要将其写入列表,而是写入IList< T>,ICollection< T>或IEnumerable< T>。即使对于异构列表,通用接口仍然可以工作,因为System.Object也可以是T。如果您决定使用堆栈或其他一些数据结构,这样做可以帮助您避免头痛。如果你需要在函数中做的只是通过它,IEnumerable< T>真的是你应该要求的全部。



另一方面,当从函数中返回一个对象时,你想给用户最丰富的一组没有他们必须施放的操作。那么在那种情况下,如果它是List< T>在内部,将副本作为List< T>返回。




参考:

< a href =http://stackoverflow.com/questions/17170/when-to-use-ilist-and-when-to-use-list> http://stackoverflow.com/questions/17170/when-to -use-ilist-and-when-use-list [ ^ ]


这篇关于差异b / w通过IList和List创建实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆