Keyed Component Collection

From XNAWiki
Jump to: navigation, search

This is an interface and a generic collection class for having the combined concept of a list and a map where items in the collection are accessible both by an index and a string key.

using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
 
    /// <summary>
    /// Interface which describes a keyed game element
    /// </summary>
    public interface IKeyedComponent
    {
 
        /// <summary>
        /// The unique key of the element
        /// </summary>
        string Key { get; }
 
    }
 
    /// <summary>
    /// A keyed collection of game elements, where elements are located
    /// both by an index and a key
    /// </summary>
    /// <typeparam name="String">The unique key for the item</typeparam>
    /// <typeparam name="TItem">The Type of the item</typeparam>
    public class KeyedComponentCollection<String, TItem> 
        :KeyedCollection<string, TItem> where TItem: IKeyedComponent
    {
        /// <summary>
        /// The method which returns the Key for the item
        /// </summary>
        /// <param name="item">The item to retrieve the key for</param>
        /// <returns>The unique key for the item</returns>
        protected override string GetKeyForItem(TItem item)
        {
            return ((IKeyedComponent)item).Key;
        }
    }