5

我試圖執行下列方式一個單獨的類(我使用VS2008 SP1):C#中的單例不在相同的名稱空間中時「不可訪問」?

namespace firstNamespace 
{ 
    class SingletonClass 
    { 
     private SingletonClass() {} 

     public static readonly SingletonClass Instance = new SingletonClass(); 
    } 
} 

當我想從不同的命名空間類訪問它(似乎這是問題,它的工作原理),如相同的命名空間:

namespace secondNamespace 
{ 
    ... 
    firstNamespace.SingletonClass inst = firstNamespace.SingletonClass.Instance; 
    ... 
} 

我得到一個編譯錯誤:

error CS0122: 'firstNamespace.SingletonClass' is inaccessible due to its protection level 

是否有人有一個想法如何解決這個問題?

非常感謝提前!

+0

非常感謝大家的快速和有益的答覆! – 2011-01-26 09:34:02

回答

10

您錯過了您班級定義中的關鍵字public

-1

您SingletonClass 不是公共的,所以不是 命名空間 裝配外部可見。

修正:評論是正確的,因爲說msdn

Classes and structs that are not nested within other classes or structs can be either public or internal. A type declared as public is accessible by any other type. A type declared as internal is only accessible by types within the same assembly. Classes and structs are declared as internal by default unless the keyword public is added to the class definition, as in the previous example. Class or struct definitions can add the internal keyword to make their access level explicit. Access modifiers do not affect the class or struct itself — it always has access to itself and all of its own members.

+1

該命名空間與內部可見性無關,該類聲明的程序集是。 – 2011-01-26 09:24:06

+0

它在名稱空間外部可見。 – 2011-01-26 09:31:18

2

的SingletonClass內部有知名度,所以如果這兩個命名空間是不同的組件,在人跡罕至的整個類。

變化

class SingletonClass 

public class SingletonClass 
3

聽起來更像單是在不同的組件。類的默認修飾符是內部的,因此只能在程序集中訪問。

2

變化

class SingletonClass 

public class SingletonClass 

紀念公開,從而訪問

甚至更​​好:

public sealed class SingletonClass 

由於成員都是靜態的:

more here

1

你類SingletonClass是在其他命名空間可見。但在其他裝配/項目中不可見。

你的課是私人的。這意味着當前項目中的所有代碼(= Assembly = .dll)都可以看到這個類。然而,該類隱藏在其他項目中的代碼。

命名空間和程序集之間存在弱相關性。一個命名空間可以存在於多個程序集中,例如mscorlib.dll和System.dll都包含System命名空間。

但通常情況下,當您在Visual Studio中創建新項目時,會得到一個新的名稱空間。

您還可以向一個Assembly添加多個名稱空間。這在創建新文件夾時自動在Visual Studio中發生。

相關問題