I have a database wrapper code like this (pseudo code):
class MyDBWrapper<objecttype> : Singleton
{
private DBDriver _Driver
Driver => Instance._Driver;
... tons of static functionality here referencing the driver
}
and then I can create custom databases from it:
class ObjectA_DB : MyDBWrapper<ObjectA_Type>
{
... all my calls using the static functionalities of the base class
}
this works very well...
Now, comes a different scenario:
I have a generic object: BaseObject and a bunch of derived objects: ObjectA, ObjectB, etc
and they all require the same database code, so I did that:
class MyGenericDB<T> : MyDBWrapper<T> where T : BaseObject
{
.. common functionality
}
and then instantiated the type specific classes like this:
class MyTypeA_DB : MyGenericDB<ObjectA_Type>
class MyTypeB_DB : MyGenericDB<ObjectB_Type>
and this compiles properly, however the singleton code is causing problem when I try to access the instance as it seems like it's recursing. Visual studio is unable to give a proper error as to what happens, but it hangs then crashes, so I am guessing a stack overflow.
The singleton code is here:
public abstract class Singleton<T> where T : class
{
private static readonly Lazy<T> _Instance = new Lazy<T>(CreateInstanceOfT, LazyThreadSafetyMode.PublicationOnly);
protected static T Instance => _Instance.Value;
private static T CreateInstanceOfT()
{
return Activator.CreateInstance(typeof(T), true) as T;
}
}
Did I miss anything obvious?
Not that used to this version of generics as my main work is in unity, and they update their core every decade, but I am pretty sure that you need your instance to be public to be allowed to read it.
When I write this, I traditionally create a private static instance of the passed type, and follow that up with a public static access function that creates that type if it does not yet exist.
A good full example for my own main engine can be found here: http://wiki.unity3d.com/index.php/Singleton .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.