通用对象池

时间:2016-06-22 19:39:45

标签: c# object-pooling

是否可以创建一个在其中创建新对象的通用对象池? 此外,如果此对象创建可以接收参数,那将是很好的。

    public interface IPoolable
    {
        void Dispose();
    }


    public class ObjectPool<T> where T : IPoolable
    {
        private List<T> pool;

        public T Get()
        {
            if(pool.count > 0)
            {
                return pool.Pop();
            }
            else
            {
                return new T(); //  <- How to do this properly?
            }
        }
    }

    public class SomeClass : IPoolable
    {
        int id;

        public SomeClass(int id)
        {
            this.id = id;
        }

        public void Dispose()
        {

        }
    }

    public class OtherClass : IPoolable
    {
        string name;
        int id;

        public OtherClass(string name, int id)
        {
            this.name = name;
            this.id = id;
        }

        public void Dispose()
        {

        }
    }

如果可以接收参数,可以像这样使用。

SomeClass a = myPool.Get(2);
OtherClass b = myOtherPool.Get("foo", 4);

如果参数不可能,这也没关系。

SomeClass a = myPool.Get();
a.id = 2;
OtherClass b = myOtherPool.Get();
b.name = "foo";
b.id = 4;

3 个答案:

答案 0 :(得分:5)

您可以使用Activator.CreateInstance Method

public static object CreateInstance(
    Type type,
    params object[] args
)

喜欢这个

return (T)Activator.CreateInstance(typeof(T), id);

但是,没有办法指定类型必须为构造函数提供参数;既不在接口声明中,也不在泛型类型约束中,也不在类继承中。

答案 1 :(得分:2)

你可以这样做:

public class ObjectPool<T>
{
    private Queue<T> _pool = new Queue<T>();

    private const int _maxObjects = 100;  // Set this to whatever

    public T Get(params object[] parameters)
    {
        T obj;

        if (_pool.Count < 1)
            obj = (T)Activator.CreateInstance(typeof(T), parameters);
        else
            obj = _pool.Dequeue();

        return obj;
    }

    public void Put(T obj)
    {
        if (_pool.Count < _maxObjects)
            _pool.Enqueue(obj);
    }
}

答案 2 :(得分:2)

我正在寻找类似的东西,并且遇到了这个问题:

TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256

这是一个非常不错的实现,我从here偷偷偷走了

它支持对从泛型类型参数继承的所有对象进行池化。

相关问题