2009-07-24 7 views
8

제네릭에 익숙하지 않습니다. 내가 IList<T> 인터페이스에서 파생하여 내 자신의 컬렉션을 구현하고 싶습니다.IList 인터페이스 구현

IList<T> 인터페이스를 구현하는 클래스에 대한 링크를 제공하거나 적어도 AddRemove 메서드를 구현하는 코드를 제공 할 수 있습니까?

답변

14

매우 강력한 이유가있는 경우가 아니면 원하는 모든 것이 있으므로 System.Collections.ObjectModel.Collection<T>에서 상속하는 것이 가장 좋습니다.

IList<T>의 구현자를 this[int] (인덱서)을 O (1) (기본적으로 일정 시간 액세스)로 구현할 필요는 없지만 이렇게하는 것이 좋습니다.

2

Mono project에서 볼 수 있습니다. 거기에 완전한 소스 코드를 사용할 수 있습니다, 당신은 어떻게 볼 수있는 몇 가지 클래스가 구현됩니다. 예 : "System.Collections.Generics.List < T>"

+2

모노 프로젝트의 홈페이지를 열면 http://anonsvn.mono-project.com/viewvc/trunk/mcs/class/corlib/System.Collections.Generic/List.cs?view=markup – Stobor

+0

다운로드해야합니까 ?? –

+0

링크가 Mono 클래스로 업데이트되었습니다. - https://github.com/mono/mono/blob/master/mcs/class/corlib/System.Collections.Generic/List.cs –

1

대부분의 경우 List<T>을 사용하거나 List<T>에서 파생시킬 수 있습니다. List<T>에서 파생 된 경우 추가 및 제거에 대한 구현이 자동으로 표시됩니다.

24

List<T>에서 파생 된 것 외에도 List<T>을 외면하고 facade 클래스에 더 많은 기능을 추가 할 수 있습니다. 목록에서 상속

class MyCollection<T> : IList<T> 
{ 
    private readonly IList<T> _list = new List<T>(); 

    #region Implementation of IEnumerable 

    public IEnumerator<T> GetEnumerator() 
    { 
     return _list.GetEnumerator(); 
    } 

    IEnumerator IEnumerable.GetEnumerator() 
    { 
     return GetEnumerator(); 
    } 

    #endregion 

    #region Implementation of ICollection<T> 

    public void Add(T item) 
    { 
     _list.Add(item); 
    } 

    public void Clear() 
    { 
     _list.Clear(); 
    } 

    public bool Contains(T item) 
    { 
     return _list.Contains(item); 
    } 

    public void CopyTo(T[] array, int arrayIndex) 
    { 
     _list.CopyTo(array, arrayIndex); 
    } 

    public bool Remove(T item) 
    { 
     return _list.Remove(item); 
    } 

    public int Count 
    { 
     get { return _list.Count; } 
    } 

    public bool IsReadOnly 
    { 
     get { return _list.IsReadOnly; } 
    } 

    #endregion 

    #region Implementation of IList<T> 

    public int IndexOf(T item) 
    { 
     return _list.IndexOf(item); 
    } 

    public void Insert(int index, T item) 
    { 
     _list.Insert(index, item); 
    } 

    public void RemoveAt(int index) 
    { 
     _list.RemoveAt(index); 
    } 

    public T this[int index] 
    { 
     get { return _list[index]; } 
     set { _list[index] = value; } 
    } 

    #endregion 

    #region Your Added Stuff 

    // Add new features to your collection. 

    #endregion 
} 
+0

하지만이 경우 컬렉션을 바인딩 할 수 없습니다. DataGridView 대신 _list 멤버를 MyCollection에 노출해야합니다. –

+0

이 작업의 단점은 무엇입니까? –

+2

최근 응답에 대해 죄송합니다. 그러나이 중 하나는 GetEnumerator가 GetEnumerator를 반환하는 IENumerator GetEnumerator를 잃어 버렸습니다. 이것은 원형 참조처럼 보입니다. 스택 오버플로 예외가 발생하지 않는 이유는 무엇입니까? – jp2code

0

는 종종 가장 빠른 방법이지만 다른 클래스에서 (예를 들어 ContextBoundObject 등)을 상속해야하는 경우 선 아래로 나중에 제한 할 수 있습니다. IList를 구현하는 것은 꽤 빠르며 위에서 지적한 것처럼 훨씬 더 많은 유연성을 제공합니다.