简体   繁体   中英

Namespaces and Using Directives

If I have a namespace like:

namespace MyApp.Providers
 {
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Globalization;
  }

Does this mean that if I create other files and classes with the same namespace, the using statements are shared, and I don't need to include them again?

If yes, isn't this a bit of a management headache?

No, it's only good for the namespace section inside the file. Not for all files inside the namespace.

If you put the using statement outside the namespace, then it applies to the entire file regardless of namespace.

It will also search the Usings inside the namespace first, before going to the outer scope.

You need to specify the using directive for any classes that you want to reference without qualification in each file where you want to use them.

Reference :

The scope of a using directive is limited to the file in which it appears.

No, it doesn't, and so no, it isn't.

Consider the fact that outside the namespace declaration, you are in the global namespace. Do using statements in that region of the source file affect the global namespace in other source files?

No. You'll need to include the namespaces in every class except on partial classes.

One side note: you're doing a very good practice of putting the using statements inside the Namespace. That's very good syntax.

Keep up the good work.

The using statements are valid for the code file in which they appear, with a minor twist; if you put the using statements inside the namespace, they are limited to the scope of that namespace, but still only within the same code file.

Usings only apply to the current file. Whether they're inside or outside the namespace declaration makes only a small difference:

The lookup order for types is as follows:

  1. start in the innermost namespace declaration
  2. look in the current namespace
  3. look in the usings of the current namespace
  4. go up to the parent namespace declaration and repeat from step 2

As a result, this program will compile fine:

namespace MyProject.Main {
    using System;

    class Program {
        public static void Main(string[] args) {
            Console.WriteLine("Hello, World!");
        }
    }
}

// in another file:
namespace MyProject.Console {
    class Test {}
}

But if you move the using System; to the top, then the compilation will fail (MyProject.Console.WriteLine doesn't exist).

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