C#中IList<T>与List<T>的区别

今天写代码是遇到这样一段:

1 IList IList11 =new List ();
2 List List11 =new List ();

百度了很多,稀里糊涂的就先记下来,做个总结。

首先IList 泛型接口是 ICollection 泛型接口的子代,并且是所有泛型列表的基接口。
它仅仅是所有泛型类型的接口,并没有太多方法可以方便实用,如果仅仅是作为集合数据的承载体,确实,IList可以胜任。
不过,更多的时候,我们要对集合数据进行处理,从中筛选数据或者排序。这个时候IList就爱莫能助了。

1、当你只想使用接口的方法时,ILis<>这种方式比较好.他不获取实现这个接口的类的其他方法和字段,有效的节省空间.

2、IList <>是个接口,定义了一些操作方法 这些方法要你自己去实现

List <>是个类型  已经实现了IList <>定义的那些方法

List <Class1> List11 =new List <Class1>(); 
是想创建一个List <Class1>,而且需要使用到List <T>的功能,进行相关操作。 
而 IList <Class1> IList11 =new List <Class1>();

只是想创建一个基于接口IList <Class1>的对象的实例,只是这个接口是由List <T>实现的。所以它只是希望使用到IList <T>接口规定的功能而已。

接口实现松耦合...有利于系统的维护与重构...优化系统流程...

 另外在提供一个datatable转list<>的代码:

 1 public IList<T> GetList<T>(DataTable table)
 2 {
 3     IList<T> list = new List<T>(); //里氏替换原则
 4     T t = default(T);
 5     PropertyInfo[] propertypes = null;
 6     string tempName = string.Empty;
 7     foreach (DataRow row in table.Rows)
 8     {
 9          t = Activator.CreateInstance<T>(); ////创建指定类型的实例
10         propertypes = t.GetType().GetProperties(); //得到类的属性
11         foreach (PropertyInfo pro in propertypes)
12         {
13             tempName = pro.Name;
14             if (table.Columns.Contains(tempName.ToUpper()))
15             {
16                 object value = row[tempName];
17                 if (value is System.DBNull)
18                 {
19                     value = "";
20                 }
21                 pro.SetValue(t, value, null);
22             }
23         }
24         list.Add(t);
25     }
26     return list;
27 } 
View Code

 其中   T t = default(T); //就是返回T的默认值。比如说T的类型是int类型的,那么这个default(T)的值就是0的;如果是string类型的话,这个返回值就是“”空字符串的。

参考博客:https://blog.csdn.net/bytxl/article/details/44033823

https://blog.csdn.net/sibaison/article/details/68059297

猜你喜欢

转载自www.cnblogs.com/Lvkang/p/9480856.html
今日推荐