C# 중첩 클래스

중첩 클래스(Nested Class)는 클래스 안에 선언되어 있는 클래스를 말합니다.

중첩 클래스


class OuterClass
{
    class NestedClass
    {

    }
}

중첩 클래스는 위와 같은 꼴로 선언 가능합니다. 객체를 생성하거나 객체의 메소드를 호출하는 방법도 보통의 클래스와 다르지 않습니다.

다른 점이 있다면, 자신이 소속되어 있는 클래스의 멤버에 자유롭게 접근할 수 있습니다. private 멤버도 가능합니다.

class OuterClass
{
    private int OuterMember;

    class NestedClass
    {
        public void DoSomething()
        {
            OuterClass outer = new OuterClass();
            outer.OuterMember = 10;
        }
    }
}

private 멤버인 OuterMember에 접근하여 값을 대입하는 코드입니다.

중첩 클래스를 사용하는 이유는 여러가지가 있겠지만, 보통은 두 가지 때문입니다.

  • 클래스 외부에 공개하고 싶지 않은 형식을 만들고자 할 때
  • 현재 클래스의 일부분처럼 표현할 수 있는 클래스를 만들고자 할 때

예제


class Configuration
{
    List<ItemValue> listConfig = new List<ItemValue>();

    public void SetConfig(string item, string value)
    {
        ItemValue iv = new ItemValue();
        iv.SetValue(this, item, value);
    }

    public string GetConfig(string item)
    {
        foreach (ItemValue iv in listConfig)
        {
            if (iv.GetItem() == item)
                return iv.GetValue();
        }

        return "";
    }

    private class ItemValue
    {
        private string item;
        private string value;

        public void SetValue(Configuration config, string item, string value)
        {
            this.item = item;
            this.value = value;

            bool found = false;
            for (int i = 0; i < config.listConfig.Count; i++)
            {
                if (config.listConfig[i].item == item)
                {
                    config.listConfig[i] = this;
                    found = true;
                    break;
                }
            }

            if (found == false)
                config.listConfig.Add(this);
        }

        public string GetItem()
        { return item; }
        public string GetValue()
        { return value; }
    }
}

class MainApp
{
    static void Main(string[] args)
    {
        Configuration config = new Configuration();
        config.SetConfig("Version", "V 5.0");
        config.SetConfig("Size", "655,324 KB");

        Console.WriteLine(config.GetConfig("Version"));
        Console.WriteLine(config.GetConfig("Size"));

        config.SetConfig("Version", "V 5.0.1");
        Console.WriteLine(config.GetConfig("Version"));
    }
}
출력 결과

V 5.0
655,324 KB
V 5.0.1

댓글 달기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다