Sto cercando di creare una classe di base Singleton generico comeCome fare un generico Singleton classe base C#
public class SingletonBase<T> where T : class, new()
{
private static object lockingObject = new object();
private static T singleTonObject;
protected SingletonBase()
{
}
public static T Instance
{
get
{
return InstanceCreation();
}
}
public static T InstanceCreation()
{
if(singleTonObject == null)
{
lock (lockingObject)
{
if(singleTonObject == null)
{
singleTonObject = new T();
}
}
}
return singleTonObject;
}
}
Ma devo fare costruttore come pubblico in uno derivato.
public class Test : SingletonBase<Test>
{
public void A()
{
}
private Test()
: base()
{ }
}
Errore di compilazione:
'Test' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test'
Come posso raggiungere questo obiettivo?
Penso che questa risposta sia probabilmente abbastanza rilevante: http://stackoverflow.com/a/380771/120243 –
Penso che il tuo codice di esempio sia sbagliato. Costruisce bene. Solo un'ipotesi, ma penso che tu intendessi che il tuo errore era correlato a "PermissionController", nel qual caso "PermissionController" deve avere un costruttore pubblico paramerterless per soddisfare il vincolo 'new()' su 'T'. –
@AlastairPitts: - Quella risposta non è ancora singleton. –