简体   繁体   English

使用泛型类型作为基类的静态成员

[英]Use generic type as a static member of base class

I have a static member in the base class of type: 我在类型的基类中有一个静态成员:

private static Dictionary<string, IEnumerable<T>> cachedList;    

This generic member should be available in all derived classes. 该泛型成员应该在所有派生类中可用。 I'm not sure how to solve it. 我不确定如何解决。

EDIT 编辑
change member to protected, does not cure my problem. 将成员更改为受保护,不能解决我的问题。
for more clarification, I used this line of code 为了进一步说明,我使用了以下代码

    public static void Cache(bool cached)
    {
        string value = typeof(T).ToString();

        if (cachedList == null)
            cachedList = new Dictionary<string, IEnumerable<T>>();
        ///some other things
    }

But every derived class has their own copy of cachedList and every classes returns "true" for the statement of cachedList == null 但是每个派生类都有自己的cachedList副本,每个类对于cachedList == null的语句均返回“ true” cachedList == null

Make this member protected instead of private. 使该成员protected而不是私有。 In this way you will be able to access exactly same dictionary instance within any derived type. 这样,您将能够访问任何派生类型中的完全相同的字典实例。

Are you asking how to create a static member of a generic class which is shared across all specializations (ie all values of T )? 您是否在问如何创建在所有专业化(即T所有值)之间共享的泛型类的静态成员? If so, read on: 如果是这样,请继续阅读:

You can't do this directly, however you could add an extra base class that your base class inherits from: 您不能直接执行此操作,但是可以添加一个继承自您的基类的额外基类:

public class NonGenericBase
{
    private static Dictionary<string, IEnumerable<object>> cachedList = new Dictionary<string, IEnumerable<object>>();

    protected static IEnumerable<T> GetCachedList<T>(string key) {
        return (IEnumerable<T>)cachedList[key];
    }

    protected static void SetCachedList<T>(string key, IEnumerable<T> value)
        where T : class
    {
        cachedList[key] = (IEnumerable<object>)value;
    }
}

And then wrap the usage of GetCachedList and SetCachedList in the generic derived class. 然后在通用派生类中包装GetCachedListSetCachedList的用法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM