2014-12-03 48 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);