Create an instacne by class name

R

Rader

Hello everybody,
I have a method "CreateInstance" defined in the following code snippet:

//To create an instance by a class's full name,but shoult check if it
can be multi-instantiated at first
public T CreateInstance<T>(string classFullName, bool
canMultiInstantiated)
{
T instanceName;
if (!canMultiInstantiated)
{
//check if the class has been instantiated
//yes: continue
//no: instanceName=TheExistingInstance
//and return the reference of the existing instance
bool existing = CheckForExistance(classFullName);//dont
know how to check
if (existing)
return TheExistingInstance; // I do want to return
the ref of the existing instacne ,but dont know how
// return default(T);
}
instanceName =
(T)Activator.CreateInstance(Type.GetType(classFullName, true, false));
return instanceName;
}

I have create an instance by the class full name successfully, but I
dont know how to check if another instance has been existing in the
current applicaiton ,can anyone help me??

Thanks very muck!
 
B

Barry Kelly

Rader said:
I have create an instance by the class full name successfully, but I
dont know how to check if another instance has been existing in the
current applicaiton ,can anyone help me??

I would suggest that you keep track of the instance when it is created,
in its constructor or always creating instances via some kind of factory
method, and keeping track of instances there.

There is no general way that I know of to enumerate all instances on the
GC heap, unless you're willing to consider debugging the application
from a separate process.

-- Barry
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top