본문 바로가기
프로그래밍/Unity 코드

System.Reflection , GetType, Getvalue, Setvaule

by 눈야옹 2016. 2. 5.

* System.Reflection 

C#에서 변수의 정보를 접근하기위해 접근자


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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
 
namespace nameReflection
{
    struct stTest
    {
        public string strData;
        public int intData;
      
    }
 
    class cReflection
    {
        // using System.Reflection 선언 혹은 참조가 필요하다.
        stTest myTestSt;
 
        void Init()
        {
            myTestSt = new stTest();
            myTestSt.strData = "stringData";
            myTestSt.intData = 101;
 
        }
 
        void Example()
        {
            //Type 가져오기
            myTestSt.GetType();
            //타입 비교
            if ( myTestSt.strData.GetType() == typeof(string))
            {
 
            }
            //필드값 접근(여기서 필드란 구조체 혹은 클래스내에 선언 되어진 변수이며 프로퍼티와는 접근이  다르다.
            //myTestSt.GetType().GetField("필드명을 string로 넣어준다");
            FieldInfo oneFieldInfo = myTestSt.GetType().GetField("필드명을 string로 넣어준다");
            string oneFieldName = oneFieldInfo.Name;// 필드의 변수명을 가져온다.
            var oneFieldValue = oneFieldInfo.GetValue(myTestSt); //해당 필드의 이름과 같은 필드의 변수값을 넣어준 object에서 가져온다.
                                                                 //만약 필드가 여러개일 경우 받아온다. 배열로 받아와 다룰수 있다.
                                                                 //myTestSt.GetType().GetFields();
                                                                 //FieldInfo[] infos
 
            //Set은 조금 다른데 set의 경우 오브젝트를 복사한후 다시 데이터를 넣어 주어서 복사 과정을 한번 거져야 한다.
            //새로운 구조체를 생성해 담아보자.
            stTest temp = new stTest();
            FieldInfo tempField = temp.GetType().GetField("변수명 입력");
            object box = temp;
            tempField.SetValue(box, "이곳에 데이터를 넣어준다.");
            temp = (stTest)box;
 
            //tip 만약 담는 데이터가 string 형이 아닐경우 위에 타입별 분류를 통해서 구분하여 담을수 있다
            
            FieldInfo tempField2 = temp.GetType().GetField("intData");
            object box2 = temp;
 
            if (tempField2.GetType() == typeof(string))
            {              
                //int형 이므로 아래 else로 가게된다.
            }
            else
            {               
                string inputData = "101010";
                int num = Convert.ToInt16(inputData);
                tempField2.SetValue(box2, num);
            }
 
            temp = (stTest)box2;
 
 
        }
 
 
    }
 
}
cs