简体   繁体   中英

Create generic List<T> in a Base class and use it in derived classes with different T

I have Base class and Manager class derived from it :

public class CBase<TC> where TC : class, new()
    {
        protected CBase() {}
        protected static ConcurrentDictionary<object, Lazy<TC>> _instances = new ConcurrentDictionary<object, Lazy<TC>>();

        public static TC GetInstance(object key)
        {
            return _instances.GetOrAdd(key, k => new Lazy<TC>(() => new TC())).Value;
        }
    }

public class CSeriesManager : CBase<CSeriesManager>
    {
        private List<CSeries.SSeries> _items = null;
        public List<CSeries.SSeries> Series 
        {
            get 
            {
                if (_items == null) _items = new List<CSeries.SSeries>();
                return _items;
            }
        }
    }

I will have several manager classes and each of them will have field similar to List with a check for NULL in getter. Is it possible to make this field generic and move it to Base class without excess boxing / casting?

This is what I have so far :

public class CBase<TC> where TC : class, new()
    {
        protected CBase() {}
        protected List<object> _items = new List<object>();
        protected static ConcurrentDictionary<object, Lazy<TC>> _instances = new ConcurrentDictionary<object, Lazy<TC>>();

        public static TC GetInstance(object key)
        {
            return _instances.GetOrAdd(key, k => new Lazy<TC>(() => new TC())).Value;
        }

        public List<TL> GetItems<TL>()
        {
            return _items.ConvertAll(x => (TL)x);
        }
    }

Does anybody have suggestions of how to improve / speed up it?

Is this what you want:

public class CBase<TC, LT> where TC : class, new()
{
    protected CBase() {}
    protected static ConcurrentDictionary<object, Lazy<TC>> _instances = new ConcurrentDictionary<object, Lazy<TC>>();

    public static TC GetInstance(object key)
    {
        return _instances.GetOrAdd(key, k => new Lazy<TC>(() => new TC())).Value;
    }

    private List<LT> _items = null;
    public List<LT> Series 
    {
        get 
        {
            if (_items == null) _items = new List<LT>();
            return _items;
        }
    }
}

public class CSeriesManager : CBase<CSeriesManager, SSeries>
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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