在Base类中创建通用List <t>,并在具有不同T的派生类中使用它

时间:2015-05-18 11:33:05

标签: c# generics

我有从它派生的Base类和Manager类:

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

我将有几个管理器类,每个类都有类似于List的字段,并在getter中检查NULL。是否可以将此字段设为通用并将其移至Base类而不会过多装箱/铸造?

这是我到目前为止所做的:

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

有人建议如何改善/加快它吗?

1 个答案:

答案 0 :(得分:2)

这就是你想要的:

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