zoukankan      html  css  js  c++  java
  • 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 static 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             try
    14             {
    15                 tempName = pro.Name;
    16                 if (table.Columns.Contains(tempName.ToUpper()))
    17                 {
    18                     object value = row[tempName];
    19                     if (value is System.DBNull)
    20                     {
    21                         value = "";
    22                     }
    23                     pro.SetValue(t, value + "", null);
    24                 }
    25             }
    26             catch (Exception)
    27             {
    28                 pro.SetValue(t, "", null);
    29             }
    30         }
    31         list.Add(t);
    32     }
    33     return list;
    34 }   

    其中   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

  • 相关阅读:
    Humidex
    Hangover(1.4.1)
    I Think I Need a Houseboat(1.3.1)
    Sum of Consecutive Prime Numbers
    Doubles
    Financial Management
    Nim算法------高僧斗法
    标题:猜灯谜
    银行管理系统
    三种例行程序(procdures,function,traps)的使用
  • 原文地址:https://www.cnblogs.com/Lvkang/p/9480856.html
Copyright © 2011-2022 走看看