ディレクティブの使用

# クラスの静的メンバーへのアクセス

特定の型をインポートし、型名で修飾せずにその型の静的メンバーを使用できるようにします。これは、静的メソッドを使用した例を示しています:

using static System.Console;

// ...

string GetName()
{
    WriteLine("Enter your name.");
    return ReadLine();
}

そして、これは静的プロパティとメソッドを使用した例を示しています:

using static System.Math;

namespace Geometry
{
    public class Circle
    {
        public double Radius { get; set; };

        public double Area => PI * Pow(Radius, 2);
    }
}

# 競合を解決するためにエイリアスを関連付ける

同じ名前のクラスを持つ可能性のある複数の名前空間を使用している場合 (System.Random など) と UnityEngine.Random )、エイリアスを使用して Random を指定できます 呼び出しで名前空間全体を使用する必要なく、どちらか一方から取得されます。

例:

using UnityEngine;
using System;

Random rnd = new Random();

これにより、コンパイラはどの Random が不明になります。 新しい変数を次のように評価します。代わりに、次のことができます:

using UnityEngine;
using System;
using Random = System.Random;

Random rnd = new Random();

これは、次のように、完全に修飾された名前空間によって他方を呼び出すことを妨げるものではありません:

using UnityEngine;
using System;
using Random = System.Random;

Random rnd = new Random();
int unityRandom = UnityEngine.Random.Range(0,100);

rnd System.Random になります 変数と unityRandom UnityEngine.Random になります

# エイリアス ディレクティブの使用

using を使用できます 名前空間またはタイプのエイリアスを設定するため。詳細については、こちらをご覧ください。

構文:

using <identifier> = <namespace-or-type-name>;

例:

using NewType = Dictionary<string, Dictionary<string,int>>;
NewType multiDictionary = new NewType();
//Use instances as you are using the original one
multiDictionary.Add("test", new Dictionary<string,int>());

# 基本的な使い方

using System;
using BasicStuff = System;
using Sayer = System.Console;
using static System.Console;  //From C# 6

class Program
{
    public static void Main()
    {
        System.Console.WriteLine("Ignoring usings and specifying full type name");
        Console.WriteLine("Thanks to the 'using System' directive");
        BasicStuff.Console.WriteLine("Namespace aliasing");
        Sayer.WriteLine("Type aliasing");
        WriteLine("Thanks to the 'using static' directive (from C# 6)");
    }
}

# 名前空間を参照

using System.Text;
//allows you to access classes within this namespace such as StringBuilder
//without prefixing them with the namespace.  i.e:

//...
var sb = new StringBuilder();
//instead of
var sb = new System.Text.StringBuilder();

# エイリアスを名前空間に関連付ける

using st = System.Text;
//allows you to access classes within this namespace such as StringBuilder
//prefixing them with only the defined alias and not the full namespace.  i.e:

//...
var sb = new st.StringBuilder();
//instead of
var sb = new System.Text.StringBuilder();

# コメント

using キーワードは、ディレクティブ (このトピック) とステートメントの両方です。

using の場合 ステートメント (つまり、IDisposable のスコープをカプセル化する) そのスコープの外でオブジェクトがきれいに破棄されるようにします) ステートメントの使用を参照してください。