Если вы действительно нужно сделать ваш пример синглтона то вот как вы это делаете.
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; }
}
Путь позвонить и установить синглтон является следующее:
// 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";
}
В качестве альтернативы вы можете добавить в конструктор следующего, чтобы избежать нулевого ссылочного исключения:
// Mark constructor as private as no one can create it but itself.
private StorageSingleton()
{
FilePath = string.Empty;
}
Слово предупреждение; делая что-нибудь глобальное или singleton, сломает ваш код в долгосрочной перспективе. Позже вы действительно должны проверить шаблон репозитория.
Что вы думаете хранить? –
Вы хотите сказать, что хотите глобальную переменную, с помощью которой вы можете получить доступ к объектам и методам? Если это так, вы можете исследовать с помощью Singleton. –
@Charlie Salts Спасибо –