C#에서의 리플렉션(Reflection)

리플렉션(Reflection)
- 런 타임시에 객체에 대한 정보를 질의하는 방법-> 실행시에 객체를 통해 클래스의 정보를 분석해내는 프로그램 기법
- using System.Reflection;
- System.Type 클래스를 이용

 

리플렉션(Reflection) 기법의 사용
- 메모리를 보유하고 있는 객체가 존재할 경우
- 객체의 형(Type) 정보를 알아낸다. (즉, 해당 객체의 Type 클래스 생성)
- 생성된 Type과 해당 객체의 메모리를 이용하여 멤버들을 호출

 

리플렉션(Reflection)의 기법
- 클래스의 능력(멤버메서드, 멤버필드 등)을 실행시에 분석
- 객체들의 속성(객체의 소속 등)을 실행시에 검사

 

리플렉션(Reflection) 기법으로 얻을 수 있는 정보
- 로딩된 Assembly에 관한 정보
- 클래스, 인터페이스 그리고 값타입의 형들에 관한 정보
 
객체의 Type가져오기
- typeof 연산자 : 클래스 타입으로 접근할 때 사용
- System.Object의 GetType() : 객체명으로 접근할 때 사용 -> 객체.GetType();
- Type.GetType() : 네임스페이스로 접근할 때 사용
- Assembly.LoadFrom() :  dll 파일에 직접 접근할 때 사용

 

using System; 
using System.Reflection;

public class GetTypeTest { 
    public static void Main() {

        //1. dll 파일로 접근하는 방법 
        Assembly a = Assembly.LoadFrom

        ("C:\WINNT\Microsoft.NET\Framework\v1.0.3705\System.dll"); 
        //LoadFrom() 메서드 : 로드하고자 하는 파일의 경로와 파일의 확장자까지 입력해야 사용

        //Assembly a = Assembly.Load("System"); 
        //Load() 메서드 : 경로를 지정불가, 실행파일이 있는 현재의 디렉터리를 기준으로 dll을 로딩후 파일의 확장자를 제

            외한 파일의 이름만을 사용.  결과로 출력된 822라는 것은 System.dll 파일 안에 존재하는 Type 클래스의 개수.

        Type [ ] type = a.GetTypes(); 
        Console.WriteLine(type.Length);         // 결과 :  822

        
        foreach(Type t in type){ 
            Console.WriteLine(t.FullName);        // 결과 :  모든 타입명을 출력.       

         }
       

 

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

        //2. 객체로 접근하는 방법 
        string s = "jabook"; 
        Type t1 = s.GetType(); 
        Console.WriteLine(t1);           //결과 : System.String

 

        //3. 런타임 시 지정된 이름으로 접근하는 방법 
        Type t2 = Type.GetType("System.String"); 
        Console.WriteLine(t2);       //결과 : System.String
         
        //4. 클래스 타입으로 접근하는 방법 
        Type t3 = typeof(System.String); 
        Console.WriteLine(t3);       //결과 : System.String
        
    }
}

 

* Type을 이용하여 클래스의 정보 추출

    using System; 
    using System.Reflection;

    public class TypeInfoTest { 
        public int temp =1000; 
        public void PrintShow(){ } 
        public static void Main() { 
            try{


                Type t = Type.GetType("TypeInfoTest");

                Console.WriteLine("[기본클래스 타입]"); 
                Console.WriteLine(t.BaseType); 
                // BaseType 속성은 Type 클래스의 읽기전용 속성,

                // 현재 Type 클래스가 직접 상속하는 클래스 타입(이름)을 반환. 
                // 만약, Object 클래스의 Type 클래스라면 상속하는 클래스가 없으므로 null을 반환.

 

                Console.WriteLine("[생성자 목록]"); 
                ConstructorInfo[ ] ctor = t.GetConstructors(); 
                for(int i=0;i<ctor.Length;i++) 
                Console.WriteLine(ctor[i]);

 

                Console.WriteLine("[메서드 목록]"); 
                MethodInfo[ ] m = t.GetMethods(); 
                for(int i=0;i<m.Length;i++) 
                Console.WriteLine(m[i]);

 

                Console.WriteLine("[변수 목록]"); 
                FieldInfo[ ] f = t.GetFields(); 
                for(int i=0;i<f.Length;i++) 
                    Console.WriteLine(f[i]); 
            }
            catch(Exception e)
            {
                Console.WriteLine(e.ToString());
            } 
        }
    }

 

[출처] https://m.blog.naver.com/PostView.nhn?blogId=delight_gruv&logNo=130071915177&proxyReferer=https%3A%2F%2Fwww.google.co.kr%2F

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED