简体   繁体   English

如何在C#中定义“匿名名称空间”?

[英]How to define “anonymous namespace” in C#?

In C++, in order to define a symbol that is only accessible within the same file, we say 在C ++中,为了定义只能在同一文件中访问的符号,我们说

namespace 
{
    class my_private_class
    { ... }
}

But can I do the same thing in C#? 但是我可以在C#中做同样的事情吗? Or do I have to say 还是我不得不说

namespace __DO_NOT_USE_OUT_OF_.xxx.cs__ 
{       
  public MyPrivateClass 
  { ... }
}

using __DO_NOT_USE_OUT_OF_.xxx.cs__;

(assuming this is in a file called xxx.cs)? (假设这在名为xxx.cs的文件中)? The later, of cause, will depend on the other programmer regards it or not. 后面的原因,将取决于其他程序员是否考虑。

There's no anonymous namespaces in C#, but you can exploit static classes : C#中没有匿名名称空间 ,但是您可以利用静态类

namespace MyNamespace // <- Just a namespace
{
    // Anonymous Namespace emulation:
    //   static class can't have instances and can't be inherited, 
    //   it's abstract and sealed
    internal static class InternalClass // or public static class
    {
        // private class, it's visible within InternalClass only  
        class my_private_class 
        { ... }
    }
}

There is no such thing in C#, we have something called access modifiers which manage the visibility of types. C#中没有这样的东西,我们有一个称为访问修饰符的东西,用于管理类型的可见性。

The usage is against a class or method, such as: 用法针对类或方法,例如:

internal class MyType 
{

}

Or 要么

protected void MyMethod() 
{

}

You will have to pick the one that applies to your scenario, here are the details: 您将必须选择一种适用于您的方案的信息,以下是详细信息:

public 上市

The type or member can be accessed by any other code in the same assembly or another assembly that references it. 该类型或成员可以由同一程序集或引用该程序集的另一个程序集中的任何其他代码访问。

private 私人的

The type or member can be accessed only by code in the same class or struct. 类型或成员只能由相同类或结构中的代码访问。

protected 受保护的

The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class. 类型或成员只能由相同类或结构中的代码或从该类派生的类中的代码访问。

internal 内部

The type or member can be accessed by any code in the same assembly, but not from another assembly. 可以通过同一程序集中的任何代码访问类型或成员,但不能从另一个程序集中访问该类型或成员。

protected internal 受保护的内部

The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. 可以通过声明了该类型或成员的程序集中的任何代码或从另一个程序集中的派生类中访问该类型或成员。 Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type. 来自另一个程序集的访问必须在从声明受保护内部元素的类派生的类声明中进行,并且必须通过派生类类型的实例进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM