开发者

How to create a generic static dictionary in a static class

开发者 https://www.devze.com 2023-04-01 03:58 出处:网络
public static class Tracking { public static List<TrackList<T>> Lists = new List<TrackList<T>>();
    public static class Tracking
    {

        public static List<TrackList<T>> Lists = new List<TrackList<T>>();

        public static List<TrackedDictionary<K,V>> Dictionaries =new List<TrackedDictionary<K,V>>()

        public static void Register<K,V>(TrackedDictionary<K,V> dictionary)
        {
            Dictionaries.Add(dictionary);
        }

        public static void Register<T> (TrackList<T> list)
        {
            Lists.Add(list);
        }
    }

public class TrackList<T> : List<T>
    {
        private string ListName = null;
        private int AvgSize;

        public TrackList ()
        { }

        public TrackList (string listname, int avgsize)
        {
            this.ListName = listname;
            this.AvgSize = avgsize;
            Tracking.Register(this);
        }

        public int GetListSize ()
        {
            return this.Count * this.AvgSize;
        }
    }

public class TrackedDictionary<开发者_如何学运维K, V> : Dictionary<K, V>
    {
        public string DictionaryName = null;
        public byte AvgSize;

        public TrackedDictionary ()
        { }

        public TrackedDictionary (string dictionaryname, byte avgsize)
        {
            this.DictionaryName = dictionaryname;
            this.AvgSize = avgsize;
            Tracking.Register(this);
        }

        public int GetDictionarySize ()
        {
            return this.Count * this.AvgSize;
        }
    }


You haven't declared Tracking as a generic type, so T, K and V have no meaning. You can do so easily enough:

public static class Tracking<T, K, V>
{
    ...
}

Note that you'll now have separate Lists, Dictionaries etc fields per concrete type. You'll need to make the methods non-generic though.

An alternative is to have a top-level non-generic class, with generic methods and generic nested types:

public static class Tracking
{
    private static class ListHelper<T>
    {
        internal static List<TrackList<T>> Lists = new List<TrackList<T>>();
    }

    private static class DictionaryHelper<K, V>
    {
        internal static List<TrackedDictionary<K,V>> Dictionaries =
            new List<TrackedDictionary<K,V>>()
    }

    public static void Register<K,V>(TrackedDictionary<K,V> dictionary)
    {
        DictionaryHelper<K, V>.Dictionaries.Add(dictionary);
    }

    public static void Register<T> (TrackList<T> list)
    {
        ListHelper<T>.Lists.Add(list);
    }
}

I'd also strongly advise against public fields like this... and against using statics widely to start with, given the problems they cause for testability.

0

精彩评论

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