C#では、クラスやメソッドをグループ化して整理するために名前空間(namespace)が使われます。 また、usingディレクティブを使うことで、名前空間を省略してコードをすっきり書けます。
class Program
{
static void Main()
{
System.Console.WriteLine("こんにちは");
}
}
using System;
class Program
{
static void Main()
{
Console.WriteLine("こんにちは");
}
}
System はC#の標準ライブラリが含まれる名前空間です。using System; を書くことで、System.Console.WriteLine を Console.WriteLine と短く書けます。namespace MyApp
{
class Greeter
{
public void SayHello()
{
Console.WriteLine("やあ!");
}
}
}
class Program
{
static void Main()
{
MyApp.Greeter g = new MyApp.Greeter();
g.SayHello();
}
}
MyApp という名前空間に Greeter クラスを定義しています。MyApp.Greeter のようにフルネームで指定します。MyApp.Models という名前空間を作り、その中に User クラスを定義してみましょう。using MyApp.Models; を活用してみましょう。