5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

usingをnamespaceの内側と外側に書いた際の違い

Last updated at Posted at 2017-10-11

usingを使用する時にnamespaceの内側と外側に書いた際の違いが分からなかったので調べてみました。

結論

検索の順序が変わる
内側から順に検索されて該当箇所が発見された時点で検索終了

検証

参考ページにある処理を試してみました。
まずはnamespace Testの中にMathクラスを作成
スクリーンショット 2017-10-11 10.09.57.png

次にusing Systemをnamespaceの内側、外側にそれぞれ記載。
Mathクラスを呼び出して動作を確認してみます。

内側に記載
スクリーンショット 2017-10-11 10.11.40.png

外側に記載
スクリーンショット 2017-10-11 10.11.16.png

結果はnamespaceの外側にusing Systemを記載すると、自作したMathクラスが先に検索されて呼び出されました。

検索順序

こちらも参考ページより抜粋した処理となります。
検索順序は以下のようになるようです。

Test.cs
using System;
using System.Collections.Generic;
using System.Linq;
//using MyCorp.TheProduct;  <-- uncommenting this would change nothing
using MyCorp.TheProduct.OtherModule;
using MyCorp.TheProduct.OtherModule.Integration;
using ThirdParty;

namespace MyCorp.TheProduct.SomeModule.Utilities
{
    class C
    {
        Ambiguous a;
    }
}
  1. クラスCの内部
  2. 名前空間の型 MyCorp.TheProduct.SomeModule.Utilities
  3. 名前空間の型 MyCorp.TheProduct.SomeModule
  4. 名前空間の型 MyCorp.TheProduct
  5. 名前空間の型 MyCorp
  6. グローバル名前空間
  7. using系

参考ページ

stackoverflow

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?