c#单独的类存储 [英] c# separate class for storage
问题描述
我使用多个类,我需要一个...让所有类和方法的全局存储。
是否是创建存储静态类的正确方法?
I use more than one class and I need a... lets say Global storage for all the class and method. Is it the right way to create a static class for storage?
public static class Storage
{
public static string filePath { get; set; }
}
还有其他方法吗?
推荐答案
如果你真的需要让你的例子是一个单例,那么这是你怎么做的。
If you really need to make your example a singleton then here is how you do it.
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; }
}
调用和设置单例的方法如下:
The way to call and set the singleton is the following:
// 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";
}
或者,您可以向构造函数中添加以下内容以避免空引用异常: / p>
Alternatively you can add into the constructor the following to avoid null reference exception:
// Mark constructor as private as no one can create it but itself.
private StorageSingleton()
{
FilePath = string.Empty;
}
警告词;使任何全局或单例将会打破你的代码长期。后来你真的应该检查存储库模式。
Word of warning; making anything global or singleton will break your code in the long run. Later on you really should be checking out the repository pattern.
这篇关于c#单独的类存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!