2014-12-03 3 views
-3

클래스가 있다고 가정하면, MainClass입니다. 이 클래스에는 MainProperty 속성이 있고 그 유형도 다른 맞춤 클래스 인 AlternateClass이라고 가정합니다. ...로 주어리플렉션을 사용하여 클래스 속성의 메소드를 호출하십시오.

public class MainClass 
{ 
    ... 
    public AlternateClass MainProperty { get; set; } 
    ... 
} 

public class AlternateClass 
{ 
    ... 
    public int someAction() 
    { 
     ... 
    } 
    ... 
} 
난 반사를 사용하여 MainPropertysomeAction() 메소드를 호출하는 방법을 알고 싶습니다

, 대안은이다 :

MainClass instanceOfMainClass = new MainClass(); 
instanceOfMainClass.MainProperty.someAction(); 
+2

? 이것은 웹상의 자료로 쉽게 다루어 져야하는 아주 기본적인 시나리오처럼 보입니다. – WeSt

답변

2

당신은 유형을 얻을 필요 및 각 레이어의 인스턴스. 리플렉션은 유형 시스템에서 특성 및 메소드를 가져 오지만 인스턴스에 대한 작업을 수행합니다.

테스트하지 않음, 아마도 몇 가지 오류가 있습니다.

//First Get the type of the main class. 
Type typeOfMainClass = instanceOfMainClass.GetType(); 

//Get the property information from the type using reflection. 
PropertyInfo propertyOfMainClass = typeOfMainClass.GetProperty("MainProperty"); 

//Get the value of the property by combining the property info with the main instance. 
object instanceOfProperty = propertyOfMainClass.GetValue(instanceOfMainClass); 

//Rinse and repeat. 
Type typeofMainProperty = intanceOfProperty.GetType(); 
MethodInfo methodOfMainProperty = typeofMainProperty.GetMethod("someAction"); 
methodOfMainProperty.Invoke(instanceOfMainProperty); 
0

GetMethod() 및 GetProperty() Reflection 메서드를 사용해야합니다. 해당 형식에 대한 각각의 메서드를 호출 한 다음 반환 된 MethodInfo 또는 PropertyInfo 개체를 원본 개체에 대해 사용합니다. 예를 들어

: 당신이 지금까지 반사와 관련된 그래서 시도 무엇

MainClass theMain = new MainClass(); 

PropertyInfo mainProp = typeof(MainClass).GetProperty("MainProperty"); 

AlternateClass yourAlternate = mainProp.GetValue(mainClass); 

MethodInfo someActionMethod = typeof(AlternateClass).GetMethod("someAction"); 

someActionMethod.Invoke(yourAlternate); 
관련 문제