Mahendra Upadhyay
Mahendra Upadhyay

Reputation: 49

Using reflection call a method through property

How shall I call "MyMethod" using reflection in below code.

I have an existing C# code which has predefined structure which I am not allow to change. I need to call a method present in a class using reflection.

In below code "_instance" contains object of "Foo". I neeed to call "MyMethod" using "PropElementHighlighter" property in Consumer class.

using System.Reflection;

    public class Foo
        {
            public void MyMethod(string Argument)
            {
               //some code
            }
        }

    public class MainWindow
    {
        private Foo _instance;
        public Foo PropElementHighlighter { get { return _instance; } }
    }

    public class Consumer
    {
        Type control = MainWindow.GetType();
        PropertyInfo l_propInfo = control.GetProperty("PropElementHighlighter", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

        MethodInfo l_HighlightMethodInfo = l_propInfo.PropertyType.GetMethod("MyMethod");
        l_HighlightMethodInfo.Invoke(l_propInfo, new object[]{"Parameter1"});
    }

I am getting error "Object does not match target type." while invoking method.

Upvotes: 1

Views: 451

Answers (1)

Dilshod K
Dilshod K

Reputation: 3082

You are getting error because you are setting property info in object of method. Try to set value of property:

Type control = mainWindow.GetType();
PropertyInfo l_propInfo = control.GetProperty("PropElementHighlighter", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
var propertyValue = l_propInfo.GetValue(mainWindow);

MethodInfo l_HighlightMethodInfo = l_propInfo.PropertyType.GetMethod("MyMethod");
l_HighlightMethodInfo.Invoke(propertyValue, new object[] { "Parameter1" });

Upvotes: 2

Related Questions