8

以下のサンプルプログラムをご覧ください。同じを含む2つの名前空間がありますstruct。での使用中の競合を避けるためにMain()、名前空間にエイリアスを指定しました。structfromを呼び出すときMain()に、のような名前空間エイリアスを介して直接呼び出すことができますtest.MyStruct::のように、演算子を使用する別のオプションもありますtest::MyStruct

なぜ::演算子が必要なのですか?エイリアスの代わりにどこで使用する必要がありますか?

using System;
using test=counter;
using duplicatecounter;

namespace counter
{
    struct MyStruct
    {

    }
}

namespace duplicatecounter
{
    struct MyStruct
    {

    }
}

class Program
{
    public static void Main()
    {
        test.MyStruct a = new test.MyStruct();
        test::MyStruct a1 = new test::MyStruct();
    }
}
4

2 に答える 2

12

これは主に、使用されているコードを考慮せずに誰かがコードを書いたときに必要です。つまり、一緒に使用されることが予想される名前空間内のクラスが重複しているか、名前空間を隠しています。

MSDN のサンプルは、Use the Global Namespace Alias の1 つのケースを示しています。

class TestApp
{
    // Define a new class called 'System' to cause problems. 
    public class System { }

    // Define a constant called 'Console' to cause more problems. 
    const int Console = 7;
    const int number = 66;

    static void Main()
    {
        // The following line causes an error. It accesses TestApp.Console, 
        // which is a constant. 
        //Console.WriteLine(number);

        global::System.Console.WriteLine(number); // ok

    }
}
于 2013-03-04T16:36:04.630 に答える
5

::演算子は同じようnamespace. に動作しますが、演算子::は識別子を検索するために使用されます。常に2つの識別子の間に配置されます

例 :

global::System.Console.WriteLine("Hello World");

ここで説明されている良い例:http://msdn.microsoft.com/en-us/library/c3ay4x3d.aspx

于 2013-03-04T16:34:33.603 に答える