Skip to content

Reflection사용하여 .dll 필드에 접근하기 #2

Description

@D-Gun

Reflection.
어떤 개발자가 Marine Class를 생성한 .dll 만 남기고 사라졌다고 생각해보자.
.dll로만 남겨졌기 때문에 파일 내부의 소스는 알수 없다.

이때 파일 내부의 필드와 메서드에 접근 할 수 있는 방법이 Reflection 을 사용하는 것이다.
먼저 필드에 접근하는 방법부터 살펴보자.

Marine m1 = new Marine(); // Marine class 객체 생성

// Type marineType = typeof(Marine) // Reflection
Type marineType = m1.Gettype(); // Reflection의 또다른 표현방법

FieldInfo hpField =
marineType.GetField("_hp", System.Reflection.BindingFlags.NonPublic, | System.Reflection.BindingFlags.Instance);

int hp1 = (int)hpField.GetValue(m1);
Console.WriteLine(hp1);

hpField.SetValue(m1,100); // 값 변경도 가능하다.

hp1 = (int)hpField.GetValue(m1);

메서드에 접근하는 방법도 있다.

MethodInfo restoreMethod = 
marineType.GetMethod("Restore",BindingFlags.NonPublic | BindingFlags.Instance); // 메서드에 접근한다.

object[] arguments = new object[1];
arguments[0] = 20;
restoreMethod.Invoke(m1, arguments);

자세한 내용이 정리되어있는 블로그를 발견했다.
블로그
attribute와 reflection까지 정리되어있다.
MSDN링크도 있으니 꼭 읽어보도록 하자.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

journalExtra attention is needed

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions