mardi 29 août 2017

Invoke Public function in Private field using Reflection C#

I need to access the public function in Private field.

Example

 public partial class Form1 : Form
{
    MainControl mainControl = new MainControl();
    public Form1()
    {
        InitializeComponent();
        var frame = mainControl.GetType().GetField("CustomControl", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        frame.GetType().GetMethod("Display").Invoke(mainControl, new object[] { });
    }
}

public class MainControl
{
    public MainControl()
    {
        CustomControl = new CustomControl();
    }

    CustomControl CustomControl;
}

public class CustomControl
{
    public CustomControl()
    {

    }

    public void Display()
    {
        MessageBox.Show("Displayed");
    }
}

Here i need to invoke the Display function in CustomControl class.

But i am getting exception with the above approach. Can anyone help me on this?





Aucun commentaire:

Enregistrer un commentaire