我正在尝试创建一个具有不同类型对象的对象池。
是否可能,如果我将一个字符串作为ps参数传递给RetriveFunction(); 它应该是一个字符串类型的新对象还是来自池中的它?
字符串将包含类型名称。
例如
Object RetriveFromPool(string typename)
{
if()//object does not present
{
//return new object of typename
}
else
{
//feth it from pool
}
}
会有可能吗?
答案 0 :(得分:2)
是的,这是可能的。 Dictionary是一种使用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;
}
答案 1 :(得分:0)
如果您的类型在编译时已知,那么使用泛型会更好:
IDictionary<Type, object> Pool = new Dictionary<Type, object>();
T RetrieveFromPool<T>()
where T : new()
{
if (Pool.ContainsKey(typeof(T)))
{
return Pool[typeof(T)];
}
return Pool[typeof(T)] = new T();
}
这是我可以设计的最安全的字符串/反射方式:
IDictionary<string, object> Pool = new Dictionary<string, object>();
object RetrieveFromPool(string typeName)
{
if (Pool.ContainsKey(typeName))
{
return Pool[typeName];
}
Type type = Type.GetType(typeName);
if (type == null)
{
return null;
}
ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes);
if (ctor == null)
{
return null;
}
object obj = ctor.Invoke(new object[0]);
Pool[typeName] = obj;
return obj;
}