2014-12-03 91 views
-3

假設您有一個類,例如MainClass。假設此類有一個屬性MainProperty,其類型也是另一個自定義類AlternateClass。鑑於爲...使用反射來調用類屬性的方法

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

public class AlternateClass 
{ 
    ... 
    public int someAction() 
    { 
     ... 
    } 
    ... 
} 

我想知道如何使用反射調用someAction()方法MainProperty,替代它的是:

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

你嘗試過什麼到目前爲止,關於反思?這似乎是一個非常基本的情況,應該可以通過網絡上的資源輕鬆進行覆蓋。 – WeSt 2014-12-03 13:32:37

回答

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()反射方法。您將調用該類型的相應方法,然後針對原始對象使用返回的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);