Egloos | Log-in


[C#] Class 내의 static 변수

Class 내에서 static으로 선언된 변수의 값은, 그 클래스를 여러번 호출할 경우에도 유지된다.

아래의 간단한 예제를 통해서 확인할 수 있다.
Visual C# 2008의 ConsoleApplication 응용 프로그램으로 생성되었으며,
main entry class Program() 내에서 test() 클래스를 두 번, 즉 t1, t2 를 두 번 선언하였다.

test class 내에는 static int 변수 m이 0으로 초기화 되며,
생성자가 호출될 때마다 m 값은 1씩 증가한다.

처음 t1 을 선언한 후에는 t1.m은 1이 되며, 두 번째 t2 를 선언한 후에는 t2.m은 2가 된다.
==================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class test
    {
        static int m=0;

        public int M
        { get { return m; } }

        public test()
        {
            m++;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            test t1 = new test();

            Console.WriteLine("t1 = {0}", t1.M);

            test t2 = new test();

            Console.WriteLine("t2 = {0}", t2.M);

            Console.ReadKey();
        }
    }
}
=====================================================

by 헤이즐넛 | 2009/10/07 09:02 | 프로그래밍 | 트랙백 | 덧글(0)

트랙백 주소 : http://hazelstyle.egloos.com/tb/5089535
☞ 내 이글루에 이 글과 관련된 글 쓰기 (트랙백 보내기) [도움말]

:         :

:

비공개 덧글

◀ 이전 페이지          다음 페이지 ▶