简体   繁体   中英

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

namespace 
{
    class my_private_class
    { ... }
}

But can I do the same thing in 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)? 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 :

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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