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中发生。

相关问题