Si vous vraiment besoin de faire votre exemple un singleton alors voici comment vous le faites.
public class StorageSingleton
{
private static readonly StorageSingleton instance;
static StorageSingleton() {
instance = new Singleton();
}
// Mark constructor as private as no one can create it but itself.
private StorageSingleton()
{
// For constructing
}
// The only way to access the created instance.
public static StorageSingleton Instance
{
get
{
return instance;
}
}
// Note that this will be null when the instance if not set to
// something in the constructor.
public string FilePath { get; set; }
}
La façon d'appeler et mettre le singleton est la suivante:
// Is this is the first time you call "Instance" then it will create itself
var storage = StorageSingleton.Instance;
if (storage.FilePath == null)
{
storage.FilePath = "myfile.txt";
}
Vous pouvez aussi ajouter dans le constructeur ce qui suit pour éviter exception de référence null:
// Mark constructor as private as no one can create it but itself.
private StorageSingleton()
{
FilePath = string.Empty;
}
Parole de Attention; faire quelque chose de global ou singleton va casser votre code à long terme. Plus tard, vous devriez vraiment vérifier le modèle de dépôt.
que pensez-vous de stocker? –
Voulez-vous dire que vous voulez une variable globale à travers laquelle vous pouvez accéder aux objets et aux méthodes? Si oui, vous pourriez enquêter en utilisant un singleton. –
@Charlie Salts Merci –