使用反射来调用类属性的方法

时间:2014-12-03 13:29:32

标签: c#

假设你有一节课,比如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 个答案:

答案 0 :(得分:2)

您需要获取每个图层的类型和实例。 Reflection从类型系统中获取属性和方法,但是对实例执行工作。

Not Test,可能有一些错误。

//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);

答案 1 :(得分: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);
相关问题