zoukankan      html  css  js  c++  java
  • 泛型学习第一天:List与IList的区别 (一)

    先看代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace List
    {
    public class Users //类Users 用户
    {
    public string Name; // 姓名
    public int Age; // 年龄
    public Users(string _Name, int _Age)
    {
    Name = _Name;
    Age = _Age;
    }
    }

    class Program
    {

    static void Main(string[] args)
    {

    Users U = new Users("jiang", 24);

    IList<Users> UILists = new List<Users>();
    //千万要注意:等式的右边是List<Users>,而不是 IList<Users>,
    //如果在List前面加一个I, 就会出现错误:抽象类或接口无法创建实例。

    UILists.Add(U);

    U = new Users("wang", 22);
    UILists.Add(U);

    List<Users> I = ConvertIListToList<Users>(UILists);

    Console.WriteLine(I[0].Name);
    Console.WriteLine(I[1].Name);

    Console.Read();
    }

    // **//// <summary>
    /// 转换IList<T>为List<T> //将IList接口泛型转为List泛型类型
    /// </summary>
    /// <typeparam name="T">指定的集合中泛型的类型</typeparam>
    /// <param name="gbList">需要转换的IList</param>
    /// <returns></returns>
    public static List<T> ConvertIListToList<T>(IList<T> gbList) where T : class //静态方法,泛型转换,
    {
    if (gbList != null && gbList.Count >= 1)
    {
    List<T> list = new List<T>();
    for (int i = 0; i < gbList.Count; i++) //将IList中的元素复制到List中
    {
    T temp = gbList[i] as T;
    if (temp != null)
    list.Add(temp);
    }
    return list;
    }
    return null;
    }
    }
    }

    IList与List的区别:

    (1)首先IList 泛型接口是 ICollection 泛型接口的子代,并且是所有泛型列表的基接口。

    它仅仅是所有泛型类型的接口,并没有太多方法可以方便实用,如果仅仅是作为集合数据的承载体,确实,IList<T>可以胜任。

    不过,更多的时候,我们要对集合数据进行处理,从中筛选数据或者排序。这个时候IList<T>就爱莫能助了。

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

    2、IList <>是个接口,定义了一些操作方法这些方法要你自己去实现
    List <>是泛型类,它已经实现了IList <>定义的那些方法

    IList <Class1> IList11 =new List <Class1>();
    List <Class1> List11 =new List <Class1>();

    这两行代码,从操作上来看,实际上都是创建了一个List<Class1>对象的实例,也就是说,他们的操作没有区别。

    只是用于保存这个操作的返回值变量类型不一样而已。

    那么,我们可以这么理解,这两行代码的目的不一样。
    List <Class1> List11 =new List <Class1>();
    是想创建一个List<Class1>,而且需要使用到List<T>的功能,进行相关操作。

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

  • 相关阅读:
    hdu 2819 Swap
    匈牙利算法
    hdu 1281 棋盘游戏
    hdu 2444 The Accomodation of Students(最大匹配 + 二分图判断)
    hdu 1045 Fire Net(最小覆盖点+构图(缩点))
    Python实现时钟
    挥之不去的DDOS
    随机数
    wchar_t的用法
    Visual Studio函数被警告安全,如何修改
  • 原文地址:https://www.cnblogs.com/azzhang/p/4078140.html
Copyright © 2011-2022 走看看