I'm curious if there's a way to tell a class being constructed to reference an existing instance.
For example:
class MyClass
{
string _name;
static List<MyClass> _existing = new List<MyClass>();
MyClass(string name)
{
foreach(MyClass existing in _existing)
{
if (existing._name == name)
{
// Set this instance to "existing"
return;
}
}
_name = name;
_existing.Add(this);
}
}
CodePudding user response:
I'm not sure if this the best approach to solve your real problem, because this sounds like a typical xy-problem. Maybe you should get familiar with singletons or dependency injection where you can control this in detail.
However, to solve this concrete issue you could use a Dictionary<string, MyClass>
:
class MyClass
{
string _name;
static Dictionary<string, MyClass> _existing = new Dictionary<string, MyClass>();
private MyClass(string name)
{
_name = name;
}
public static MyClass GetFromName(string name)
{
if(_existing.TryGetValue(name, out MyClass instance))
return instance;
MyClass newInstance = new MyClass(name);
_existing.Add(name, newInstance);
return newInstance;
}
}
CodePudding user response:
I think you need to implement a holder of the particles, that can direct creation or re-use to existing objects. The constructor of each class, cannot be responsible to see if it already exists, since merely newing it up to inspect, allocates resources for it. Your particle holder (Single instance) would then use a dictionary/hash/list/collection to return existing based on name, or create and cache new instances for future use.