Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

For me

[Unity] 4) Reflection 과 Attribute 본문

Unity/이론

[Unity] 4) Reflection 과 Attribute

GiveZero 2023. 2. 28. 22:39

Reflection

개념

런타임 객체의 형식 정보를 들여다 보는 기능

System.Object 형식 정보를 반환하는 GetType() 메소드 보유

즉, 모든 데이터 형식은 System.Object 형식을 상속하므로 GetType() 메소드 또한 보유

 

Object.GetType() 메소드는 System.Type 형식 결과를 반환

Type 형식은 .NET 데이터 형식의 모든 정보(메소드, 필드, 프로퍼티 등)를 표현

{
	int a= 0;
	Type type = a.GetType();
	FieldInfo[] fields = type.GetFields();
    
    foreach ( FieldInfo field in fields)
    	Console.WriteLine("Type:{0}, Name{1}", field.FieldType.Name, field.Name);
}

 

검색

메소드 반환형식 설명
GetConstructors() ConstructorInfo[] 해당 형식의 모든 생성자 목록을 반환
GetEvents() ConstructorInfo[] 해당 형식의 이벤트 목록을 반환
GetFields() ConstructorInfo[] 해당 형식의 필드 목록을 반환
GetGenericArguments() Type[] 해당 형식의 형식 매개 변수 목록을 반환
GetInterfaces() Type[] 해당 형식이 상속하는 인터페이스 목록을 반환
GetMembers() MemberInfo[] 해당 형식의 멤버 목록을 반환
GetMethods() MethodInfo[] 해당 형식의 메소드 목록을 반환
GetNestedTypes() Type[] 해당 형식의 내장 형식목록을 반환
GetProperties() PropertyInfo[] 해당 형식의 프로퍼티 목록을 반환

 

System.Type.Get[ ]() 검색옵션

System.Reflection.BindingFlags 열거형 상수 조합

Type type = a.GetType();

//public 인스턴스 필드 조회
var fields1 = type.GetFields(BindingFlags.Public | BindingFlags.Instance);

//비 public 인스턴스 필드 조회
var fields2 = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

//public 정적 필드 조회
var fields3 = type.GetFields(BindingFlags.Public | BindingFlags.Static);

//비 public 정적 필드 조회
var fields4 = type.GetFields(BindingFlags.NonPublic | BindingFlags.Static);

 

리플렉션을 이용한 객체 생성 및 활용

System.Activator 클래스에게 System.Type 객체를 입력하여 인스턴스를 생성

PropertyInfo 클래스의 GetValue()로 값을 읽고, SetValue()로 값 기록

MethodInfo 클래스의 Invoke()메소드를 통해 호출

어플리케이션에 플러그인 아키텍쳐를 적용할 때 유용함

class Profile
{
	public Name{get;set;}
    public Phone{get;set;}
    
    public void Print()
    {
		// TODO
	}
}

static void Main()
{
	Type type = typeof(Profile);
    profile profile = (Profile)Activator.CreateInstacne(type);
    
    PropertyInfo name = type.PropertyInfo("Name");
    PropertyInfo phone = type.PropertyInfo("Phone");
    
    name.SetValue(profile,"홍길동",null);
    phone.SetValue(profile,"010-1234-5678",null);
    
    Console.WriteLine("{0}, {1}",
    	name.GetValue(profile,null),phone.GetValue(profile,null));
        
    MethodInfo method = type.GetMethod("Print");
    method.Invoke(profile,null);
}

 

Attribute

개념

메타 데이터를 담는 코드 요소

컴파일을 거치면 실행파일 안에 저장되며 컴퓨터가 런타임에 읽을 수 있음(주석과는 다름)

활용

[ AttributeName (Attribute매개변수) ]

class MyClass
{
	[Obsolete("Please Use NewMethod()")]
    public void OldMethod()
    {
		//TODO
    }
    
    public void NewMethod()
    {
    	//TODO
    }
}

 

사용자 정의 애트리뷰트

System.Attribute를 상속하여 사용자 정의 애트리뷰터 선언

class History : System.Attribute
{
	private string name;
    public doublic Version{get;set}
    public History(string name)
    {
    	this.name = name;
        Version = 1.0;
    }
}

[History("TOM", Version = 0.1)]
[Histroy("Jerry", Version = 0.2)]
class MyClass
{
	public void Func()
    {
    	//TODO
    }
}

 

'Unity > 이론' 카테고리의 다른 글

[Unity] 6) Addressable  (0) 2023.03.03
[Unity] 5) Nullable  (0) 2023.03.01
[Unity] 3) Exception  (0) 2023.02.28
[Unity] 2) Delegate 와 Event  (0) 2023.02.28
[Unity] 1) Invoke 와 Coroutine의 차이  (0) 2023.02.28