c#单独存储类
我使用多个类,我需要一个...让我们说全球存储的所有类和方法。 这是创建存储静态类的正确方法吗?c#单独存储类
public static class Storage
{
public static string filePath { get; set; }
}
还有其他方法可以做到吗?
如果你真的需要做你的榜样单身那么这里是你如何做到这一点。
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;
}
的字警告;从长远来看,任何全局或单例都会破坏你的代码。稍后你真的应该检查存储库模式。
谢谢,非常详细的例子。 – 2009-08-20 07:46:29
你应该看看仓库模式:
实现这种模式的http://martinfowler.com/eaaCatalog/repository.html
的一种方式是通过使用ORM的的股份公司NHibernate的:
感谢您的快速,我正在研究它。 – 2009-08-14 06:14:39
但是对于你的例子,我认为它对我来说太多了。我根本不需要那种存储。 – 2009-08-14 06:23:51
你可以考虑使用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;
}
}
}
应用辛格尔顿到您的原班:
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;
我喜欢看到单身的C#,落实。
public class Singleton
{
public static readonly Singleton instance;
static Singleton()
{
instance = new Singleton();
}
private Singleton()
{
//constructor...
}
}
C#保证您的实例不会被覆盖,你的静态构造函数的保证,你将有它使用的第一次之前你静态属性实例化。
奖励:根据静态构造函数的语言设计,它是线程安全的,没有双重检查锁定:)。
您认为要存储什么? – 2009-08-14 06:12:16
你的意思是说你想要一个全局变量,通过它你可以访问对象和方法?如果是这样,你可以使用单例进行调查。 – 2009-08-14 06:19:39
@Charlie盐酸盐谢谢 – 2009-08-19 16:32:19