是的,這是可能的。字典是存儲鍵值對與O(1)查找一個方便的方法和Activator
是能夠實例化僅在運行時已知的類型:
private IDictionary<string, object> _objectPool;
object RetriveFromPool(string typeName)
{
if(_objectPool.ContainsKey(typeName))
{
return _objectPool[typename]; // return from the pool
}
return Activator.CreateInstance(Type.GetType(typeName)); // Try to create a new object using the default constructor
}
作爲然而替代(確保編譯時間類型檢查)你不妨使用泛型來實現這一目標:
private IDictionary<Type, object> _objectPool;
public T RetrieveFromPool<T>() where T : new()
{
Type type = typeof(T);
return _objectPool.ContainsKey(type) ? (T)_objectPool[type] : new T();
}
// Update - add a couple of templates for add methods:
public void AddToPool<T>() where T : new
{
_objectPool[typeof(T)] = new T();
}
public void AddToPool<T>(T poolObject) where T : new
{
_objectPool[typeof(T)] = poolObject;
}
是否可以避免反射? – 2012-02-10 13:31:32
@NIleshLanke查看更新。 – 2012-02-10 13:34:20
@ rich.okelly補償你,你一直在竊取我的想法!我們正在同一頁面上思考。儘管如此,你在第一個樣本中有一個錯誤。你永遠不會存儲新實例化的對象。實際上,第二個也一樣。 – Zenexer 2012-02-10 13:35:47