开发者

C#中IList 与 List 的区别小结

开发者 https://www.devze.com 2024-08-12 14:07 出处:网络 作者: 那个那个鱼
目录1. 定义和实现方式:2. 泛型支持:3. 功能和性能:List转IList的方法总结:IList 接口和 List 类是 C# 中用于集合操作的两个重要的类型。
目录
  • 1. 定义和实现方式:
  • 2. 泛型支持:
  • 3. 功能和性能:
  • List转IList的方法
  • 总结:

IList 接口和 List 类是 C# 中用于集合操作的两个重要的类型。

javascript

它们之间的区别如下:

1. 定义和实现方式:

IList 接口是一个抽象接口,定义了一组用于操作列表的方法和属性。它是 System.Collections 命名空间中的一部分,可以被其他类实现。

List 类是 IList 接口的一个具体实现,它提供了 IList 接口中定义的所有方法和属性的具体实现。List 类位于 System.Collections.Generic 命名空间中。

2. 泛型支持:

IList 接口是非泛型接口,它可以存储任意类型的对象。

List 类是泛型类,它可以指定存储的元素类型,并在编译时进行类型检查,提供更好的类型安全性。

3. 功能和性能:

IList 接口定义了一组基本的列表操作方法,如添加、删除、插入、索引访问等。它提供了对列表的基本操作支持,但不提供具体的实现。

List 类在 IList 接口的基础上提供了更多的功能和性能优化。它使用动态数组来存储元素,可以高效地进行插入、删除和索引访问操作。此外,List 类还提供了一些额外的方法,如排序、查找等。

错误使用案例

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<stringhttp://www.devze.com>();
         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转IList的方法

/// <summary>
/// List转IList公共方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="listObjects"></param>
/// <reandroidturns></rehttp://www.devze.comturns>
protected static IList<T> ConvertToGenericList<T>(IList listObjects)
{
      IList<T> convertedList =js new List<T>(listObjects.Count);
 
      foreach (object listObject in listObjects)
      {
           convertedList.Add((T)listObject);
      }
 
      return convertedList;
}

总结:

  • IList 接口是一个抽象的列表操作接口,可以被其他类实现。
  • List 类是 IList 接口的一个具体实现,提供了更多的功能和性能优化。

到此这篇关于C#中IList 与 List 的区别小结的文章就介绍到这了,更多相关C# IList List 内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)! 

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号