欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#中IList 與 List 的區(qū)別小結(jié)

 更新時(shí)間:2024年04月15日 09:17:38   作者:那個(gè)那個(gè)魚  
IList 接口和 List 類是 C# 中用于集合操作的兩個(gè)重要的類型,本文主要介紹了C#中IList 與 List 的區(qū)別小結(jié),具有一定的參考價(jià)值,感興趣的可以了解一下

IList 接口和 List 類是 C# 中用于集合操作的兩個(gè)重要的類型。

它們之間的區(qū)別如下:

1. 定義和實(shí)現(xiàn)方式:

IList 接口是一個(gè)抽象接口,定義了一組用于操作列表的方法和屬性。它是 System.Collections 命名空間中的一部分,可以被其他類實(shí)現(xiàn)。
List 類是 IList 接口的一個(gè)具體實(shí)現(xiàn),它提供了 IList 接口中定義的所有方法和屬性的具體實(shí)現(xiàn)。List 類位于 System.Collections.Generic 命名空間中。

2. 泛型支持:

IList 接口是非泛型接口,它可以存儲(chǔ)任意類型的對(duì)象。
List 類是泛型類,它可以指定存儲(chǔ)的元素類型,并在編譯時(shí)進(jìn)行類型檢查,提供更好的類型安全性。

3. 功能和性能:

IList 接口定義了一組基本的列表操作方法,如添加、刪除、插入、索引訪問等。它提供了對(duì)列表的基本操作支持,但不提供具體的實(shí)現(xiàn)。
List 類在 IList 接口的基礎(chǔ)上提供了更多的功能和性能優(yōu)化。它使用動(dòng)態(tài)數(shù)組來(lái)存儲(chǔ)元素,可以高效地進(jìn)行插入、刪除和索引訪問操作。此外,List 類還提供了一些額外的方法,如排序、查找等。

錯(cuò)誤使用案例

using System;
using System.Collections.Generic;
namespace DemoApplication{
   class Demo{
      static void Main(string[] args){
         IList<string> ilist = new IList<string>();
         //This will throw error as we cannot create instance for an IList as it is an interface.
         ilist.Add("Mark");
         ilist.Add("John");
         foreach (string list in ilist){
            Console.WriteLine(list);
         }
      }
   }
}

下面的是正確案例

using System;
using System.Collections.Generic;
namespace DemoApplication{
   class Demo{
      static void Main(string[] args){
         IList<string> ilist = new List<string>();
         ilist.Add("Mark");
         ilist.Add("John");
         List<string> list = new List<string>();
         ilist.Add("Mark");
         ilist.Add("John");
         foreach (string lst in ilist){
            Console.WriteLine(lst);
         }
         foreach (string lst in list){
            Console.WriteLine(lst);
         }
         Console.ReadLine();
      }
   }
}

List轉(zhuǎn)IList的方法

/// <summary>
/// List轉(zhuǎn)IList公共方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="listObjects"></param>
/// <returns></returns>
protected static IList<T> ConvertToGenericList<T>(IList listObjects)
{
      IList<T> convertedList = new List<T>(listObjects.Count);
 
      foreach (object listObject in listObjects)
      {
           convertedList.Add((T)listObject);
      }
 
      return convertedList;
}

總結(jié):

  • IList 接口是一個(gè)抽象的列表操作接口,可以被其他類實(shí)現(xiàn)。
  • List 類是 IList 接口的一個(gè)具體實(shí)現(xiàn),提供了更多的功能和性能優(yōu)化。

到此這篇關(guān)于C#中IList 與 List 的區(qū)別小結(jié)的文章就介紹到這了,更多相關(guān)C# IList List 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

最新評(píng)論