December 2007
Intermediate to advanced
896 pages
19h 57m
English
Your generic type needs to be created with a type argument that must support the members of a particular interface such as the IDisposable interface.
Use constraints to force the type arguments of a generic type to be of a type that implements one or more particular interfaces:
public class DisposableList<T> : IList<T>
where T : class, IDisposable { private List<T> _items = new List<T>(); // Private method that will dispose of items in the list private void Delete(T item) { item.Dispose(); } // IList<T> Members public int IndexOf(T item) { return (_items.IndexOf(item)); } public void Insert(int index, T item) { _items.Insert(index, item); } public T this[int index] } get {return (_items[index]);} set {_items[index] = value;} } public void RemoveAt(int index) } Delete(this[index]); _items.RemoveAt(index); } // ICollection<T> Members public void Add(T item) { _items.Add(item); } public bool Contains(T item) { return (_items.Contains(item)); } public void CopyTo(T[] array, int arrayIndex) { _items.CopyTo(array, arrayIndex); } public int Count { get {return (_items.Count);} } public bool IsReadOnly { get {return (false);} } // IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { return (_items.GetEnumerator()); } // IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return (_items.GetEnumerator()); } // Other members public void Clear() { for (int index = 0; index < _items.Count; index++) { Delete(_items[index]); } ...Read now
Unlock full access