mercredi 21 octobre 2020

How can I get an instance of property using reflection, then call that property's method?

Consider the following code:

using System;
using System.Reflection;

class Program 
{
    public static void Main (string[] args) 
    {
        var myClass = new MyClass {MyProp = new MyProperty()};
        var propertyTargeter = new PropertyTargeter {TargetProp = "MyProp", ValueToPass = 10};
        myClass.ExecuteTargeter(propertyTargeter);
    }
}

public class PropertyTargeter
{
    public string TargetProp {get; set;}
    public int ValueToPass {get; set;}
}

public class MyProperty
{
    public void PrintValue(int value)
    {
        Console.WriteLine(value);
    }
}

public class MyClass
{
    public MyProperty MyProp {get; set;}

    public void ExecuteTargeter(PropertyTargeter pt)
    {
        PropertyInfo pi = this.GetType().GetProperty(pt.TargetProp);
        MethodInfo mi = pi.GetType().GetMethod("PrintValue");
        mi.Invoke([property instance goes here], new object[] {pt.ValueToPass});
    }
}

I would like to be able to call the PrintValue method of myClass.MyProp, but I'm not sure how to get the instance of the property. To be clear, I don't want to create a new instance of MyProperty -- I want to access the instance already declared in myClass.MyProp. How can I do that?





Aucun commentaire:

Enregistrer un commentaire