我使用多個類,我需要一個...讓我們說全球存儲的所有類和方法。 這是創建存儲靜態類的正確方法嗎?c#單獨存儲類
public static class Storage
{
public static string filePath { get; set; }
}
還有其他方法可以做到嗎?
我使用多個類,我需要一個...讓我們說全球存儲的所有類和方法。 這是創建存儲靜態類的正確方法嗎?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