typeof()
컴파일 타임에 객체의 타입을 얻는다. 반환 타입은 System.Type 이다.
사용예시)
typeof(타입명)
인스턴스가 아닌 타입명만 들어갈 수 있다. 예를들어,
using System;
class Temporary {}
public static void Main(string[] args) {
Temporary tmp = new Temporary();
Console.WriteLine(typeof(Temporary));
// Console.WriteLine(typeof(tmp)); // Compile Error
}
Temporary 형으로 선언된 인스턴스 tmp는 typeof의 인자로 들어갈 수 없다.
.GetType()
런타임에 생성된 인스턴스의 타입을 얻는다. 반환 타입은 System.Type 이다.
사용예시)
(인스턴스).GetType()
typeof를 통해 인스턴스의 타입을 비교할 수 있다.
다음 코드를 보면,
using System;
class Base {}
class Derived : Base {}
public static void Main(string[] args) {
Base parent = new Base();
Base child = new Derived(); // Upcasting
Console.WriteLine(child.GetType() == typeof(Base)); // false
Console.WriteLine(child.GetType() == typeof(Derived)); // true
}
child.GetType() == typeof(Base) 는 False,
child.GetType() == typeof(Derived) 는 True를 반환한다.
부모클래스로 업캐스팅된 child 인스턴스의 경우 Base가 아닌 Derived 타입임을 알 수 있다.
응용하기
using System;
using System.Collections.Generic;
public class Product {}
public class Electronic : Product {}
public class Food : Product {}
public class Furniture : Product {}
public class Clothes : Product {}
public class Shop {
private Dictionary<Type, int> products = new Dictionary<Type, int>() {
[typeof(Electronic)] = 51,
[typeof(Food)] = 120,
[typeof(Furniture)] = 38,
[typeof(Clothes)] = 73
};
public int GetCount(Type productType) {
return products[productType];
}
public void CheckProducts() {
Product p = new Food();
Console.WriteLine(GetCount(p.GetType())); // 120
Console.WriteLine(GetCount(typeof(Electronic))); // 51
}
}
Product p = new Food() 에서 p는 Food에서 Product 타입으로 업캐스팅된 Food 타입이다.
GetCount 함수에 인자로 p.GetType()을 넣게 되면 Food 타입에 해당하는 값인 120이 출력된다.
인자로 typeof(Electronic)을 넣게 되면 Electronic 타입에 해당하는 값인 51이 출력된다.