我使用多个类,我需要...让我们说所有类和方法的全局存储。 这是为存储创建静态类的正确方法吗?
public static class Storage
{
public static string filePath { get; set; }
}
或者还有其他方法吗?
答案 0 :(得分:3)
您可以考虑使用Singleton设计模式: Implementing Singleton in c#
例如
using System;
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
答案 1 :(得分:3)
如果真的需要让你的例子成为单身人士,那么你就是这样做的。
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;
}
警告词;从长远来看,制作任何全局或单身的东西都会破坏你的代码。稍后您应该检查存储库模式。
答案 2 :(得分:1)
答案 3 :(得分:0)
将Singleton应用于原始类:
public class Storage
{
private static Storage instance;
private Storage() {}
public static Storage Instance
{
get
{
if (instance == null)
{
instance = new Storage();
}
return instance;
}
}
public string FilePath { get; set; }
}
用法:
string filePath = Storage.Instance.FilePath;
答案 4 :(得分:0)
我喜欢在C#中看到单例的实现。
public class Singleton
{
public static readonly Singleton instance;
static Singleton()
{
instance = new Singleton();
}
private Singleton()
{
//constructor...
}
}
C#保证您的实例不会被覆盖,并且您的静态构造函数保证您在第一次使用静态属性之前将其实例化。
Bonus:根据静态构造函数的语言设计,它是线程安全的,没有双重检查锁定:)。