2
0

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 3 years have passed since last update.

namespaceの使い方を確認してみた

Posted at

2022.5.10 10日目 

やること

今回はnamespaceに関してどうやって使用するのかを確認していきます。
こういうときにしかしっかり調べなさそうなのでやっていきます。

きっかけ

そもそもnamespaceは、チームで制作しているゲームのコードによくみられる印象があります。
今回、社内で使用しているプログラムコードにnamespaceが使用されていて調べてみる事にしました。

参考資料

namespaceってなんぞや

namespaceとは、日本語では名前空間といい、関連するクラスを整理するための名前付けのスキームのことです。
(スキームとは、体系的な計画、計画をともなう枠組み、基本的な仕組みのことだそうです)

名前空間を定義するために「namespace」を使います。
namespaceの{}で囲った中でクラスを定義することで、クラスが名前空間に属することになります。

「関連のあるものでまとめる」仕組みこそが名前空間であり、そのような意味合いでもクラスを名前空間で階層化して管理します。

↓サンプルコード

namespace School {

    namespace Student {

        class Profile {
        }

        class Activities {

        }

        namespace Subject {
            class Test {
            }

            class Rating {
            }
        }
    }
}

このサンプルコードは以下のように書き換える事も出来ます。

namespace School.Student {

    class Profile {
    }

    class Activities {
    }
}

namespace School.Student.Subject {

    class Test {
    }

    class Rating {
    }
}

namespaceで定義したクラスを使用する方法

using School.Student;
using School.Student.Subject;

using で名前空間を定義します。(しなくても使用することはできますが、コードの量が増えるので、最初に定義しておいた方が便利です)

Profile profile = new Profile();
Activities activities = new Activities();
testc test = new test();
Rating image = new Rating();

内容を呼び出すときは、上のコードのように呼び出します。

終わりです。

2
0
2

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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?