Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C#에서 List와 IList의 차이점은 무엇입니까?

<시간/>

C#에서 List와 IList의 주요 차이점은 List는 인덱스로 액세스할 수 있는 개체 목록을 나타내는 클래스이고 IList는 인덱스로 액세스할 수 있는 개체 컬렉션을 나타내는 인터페이스라는 것입니다. IList 인터페이스는 ICollection 및 IEnumerable의 두 인터페이스에서 구현됩니다.

List 및 IList는 개체 집합을 나타내는 데 사용됩니다. 정수, 문자열 등의 개체를 저장할 수 있습니다. List 또는 IList의 요소를 삽입, 제거, 검색 및 정렬하는 방법이 있습니다. List와 IList의 주요 차이점은 List는 구체적인 클래스이고 IList는 인터페이스라는 것입니다. 전반적으로 List는 IList 인터페이스를 구현하는 구체적인 유형입니다.

예시 1

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);
         }
      }
   }
}

예시 2

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();
      }
   }
}

출력

위 코드의 출력은

Mark
John
Mark
John