我在C#中編寫一個應用程序,我需要一個單例對象;所以只有該類的一個對象。但是這個類需要有一個對系統另一個類的對象的引用列表,所以我添加了這樣一個列表作爲屬性,然後創建了一個方法來向它添加另一個對象。參數類型在單例實現中不易訪問
我認爲這是正確的,但我得到一個錯誤,其中參數類型(列表中的類)不如方法(下面的代碼中的AddNew
)可訪問。
這是我到目前爲止有:
namespace One {
public sealed class Singleton {
// Only instance of the class:
private static readonly Singleton instance = new Singleton();
private List<MyOtherClass> list;
static Singleton() { }
private Singleton() {
list = new List<MyOtherClass>();
}
// Accessor to the property (the instance per se):
public static Singleton Instance {
get {
return instance;
}
}
// Method to add a new object to the list:
public void AddNew(MyOtherClass newObject) {
list.Add(newObject);
}
}
}
的類,它的對象是該列表中的定義如下:
namespace One {
class MyOtherClass {
... // With private attributes and public constructor and methods.
}
}
可能在哪裏這個問題呢?難以完成我想要的嗎?該類是公共的,並駐留在定義單例類的相同名稱空間中。
我看到一個類的默認保護級別是「內部」,我認爲如果我沒有另外指定,他們會公開。實際上,直到我讀到這些答案時,我從來沒有聽說過「內部」級別,如果我要學習和正確使用它,我需要認真閱讀C#。謝謝你的回答,我想我會在那時做單身課。 –
@JamesRussell:所有你需要記住的是,一般來說,如果你沒有指定任何訪問修飾符,C#將默認爲它可以指定的最私有的。 –