如何在静态类中创建通用静态字典

时间:2011-08-31 09:52:56

标签: c# generics static

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

1 个答案:

答案 0 :(得分:8)

您尚未将Tracking声明为通用类型,因此TKV没有任何意义。你可以很容易地做到这一点:

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

请注意,您现在每个具体类型都有单独的 ListsDictionaries等字段。您需要使这些方法不是通用的。

另一种方法是使用泛型非泛型类,使用泛型方法和通用嵌套类型:

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

我还强烈建议不要使用这样的公共字段......并且考虑到它们导致可测试性的问题,反对广泛使用静态。