static and instance

2011. 3. 11. 00:49 from PROGRAMMING/C#.NET

■ 클래스나 필드에 static을 썼을때와 쓰지 않았을 때, 데이터 접근 방법에 차이가 생긴다.

 

■ 클래스의 멤버(혹은 구조체 멤버)에 접근 할 수 있는 방법은,

 1. 정적인(static) 방법(다이렉트로 데이터에 접근 가능)과

 2. 인스턴스(instance, =객체)를 생성해 놓은 후 접근하는 것이 있다.

 

즉, 바로 데이터에 접근하고 싶다면 static 키워드 사용, static을 사용하지 않았다면 인스턴스로 접근 가능하다.

 

static과 instance 접근에 있어 클래스와 구조체 멤버의 차이

using System;

//클래스
public class Product
{
    public static string ModelName; // 상품명 저장 공간-static 사용
    public int UnitPrice;  // 단가-static 사용하지 않음
}

//구조체
public struct Customer
{
    public static string Name; //고객명-static 사용
    public int Age; // 나이-static 사용하지 않음
}

//실행영역
public class Program
    {
        public static void Main(string[] args)
        {
            // Product 클래스의 필드(멤버 변수)를 사용하고자 할때,
            Product.ModelName = "컴퓨터"; //정적(static) 접근
            Product pro = new Product(); // 인스턴스(Instance, 객체) 생성
            pro.UnitPrice = 1000; //객체를 통해 UnitPrice에 접근 가능
            Console.WriteLine("모델명 : {0}, 가격 : {1}", Product.ModelName, pro.UnitPrice);
           
            //Customer 구조체의 멤버에 접근하고자 할때,
            Customer.Name = "홍길동"; //정적(static) 접근
            Customer cust; // 구조체형 변수 선언으로 접근 가능-구조체는 값 타입 므로
            cust.Age = 21;
            Console.WriteLine("고객명 : {0}, 나이 : {1}", Customer.Name, cust.Age);
        }
    }

'PROGRAMMING > C#.NET' 카테고리의 다른 글

Properties  (0) 2011.03.13
Constructor and Destructor  (0) 2011.03.12
chap.3 타입 2. 참조 타입  (0) 2011.03.08
chap.3 타입 1.값 타입  (0) 2011.03.08
[0304과제] 연산자 종류(C, C#)  (0) 2011.03.06
Posted by 마마필로 :