네임스페이스(Namespaces)
네임스페이스는 C#프로그램 내에서 두 가지 방법으로 많이 사용된다.
첫째, .NET Framework 클래스는 네임스페이스를 사용하여 많은 클래스를 구성한다.
둘째, 고유한 네임스페이스를 선언하면 대규모 프로그래밍 프로젝트에서 클래스 및 메서드 이름의 범위를 제어할 수 있다.
1.네임스페이스 액세스
C# 스크립트를 보면 대부분 using 지시문 으로 시작한다.
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; |
C, C++에서 #include<stdio.h> 혹은 #include<iostream>비슷하다 생각하면 될것이다.
예제)
//첫번째 방식 |
2.범위 제어
프로젝트의 규모가 커질수록 이름이 겹치는 경우가 많아진다
예를 들어 똑같은 팔이여도 주인공의 팔, 적의 팔 두가지가 있고 했을떄, 주인공의 팔은 arm1, 저의 팔은 arm2 이런식으로 정하는 것이 아닌, 똑같이 arm으로 만들어 주는 기능이 네임스페이스이다.
이 기능을 사용하면 스크립트 파악도 쉽고 작성시 햇갈림을 줄여줄 것이다.
예제)
namespace SampleNamespace
{
class SampleClass
{
public void SampleMethod()
{
System.Console.WriteLine(
"SampleMethod inside SampleNamespace");
}
}
// Create a nested namespace, and define another class.
namespace NestedNamespace
{
class SampleClass
{
public void SampleMethod()
{
System.Console.WriteLine(
"SampleMethod inside NestedNamespace");
}
}
}
class Program
{
static void Main(string[] args)
{
// Displays "SampleMethod inside SampleNamespace."
SampleClass outer = new SampleClass();
outer.SampleMethod();
// Displays "SampleMethod inside SampleNamespace."
SampleNamespace.SampleClass outer2 = new SampleNamespace.SampleClass();
outer2.SampleMethod();
// Displays "SampleMethod inside NestedNamespace."
NestedNamespace.SampleClass inner = new NestedNamespace.SampleClass();
inner.SampleMethod();
}
} } |
클래스 SampleClass와 NestedNameSpace안에 SampleClass가 이름이 같지만 서로 다름을 알 수있다.
728x90
댓글