mercredi 15 juin 2016

How to get event target method through reflection

I have a very simple class:

public delegate void ChangedEventHandler_OUT();
public class Plugin
{

    public Plugin(string _pluginName)
    {
        pluginName = _pluginName;
    }

    public string pluginName;
    public string member1;
    public string member2;

    public event ChangedEventHandler_OUT OnStatusChange1_OUT;
    public event ChangedEventHandler_OUT OnStatusChange2_OUT;

    public void PluginAction()
    {
        MessageBox.Show("ACtion from plugin " + pluginName);
    }

}

in the Main I create two instances and connect their events:

var plugin1 = new Plugin("plugin1") { member1 = "AAA1", member2="BBB1"};
var plugin2 = new Plugin("plugin2") { member1 = "AAA1", member2 = "BBB1" };

plugin1.OnStatusChange1_OUT += plugin2.PluginAction;

now I'm perfectly aware that this makes little sense but I want to go deep in reflection and get all information I can get:

MEMBERS

lbxInfo.Items.Add("Plugin1 member:");
Type type = typeof(Plugin);
foreach (var field in type.GetFields())
{
        string strName = field.Name; // Get string name
        string strType = field.FieldType.Name;
        string strValue = (string)field.GetValue(plugin1);
        lbxInfo.Items.Add(strType + " " + strName + " = " + strValue);
}

and this works fine enter image description here

Now I would like to get all information about events:

EVENTS:

lbxInfo.Items.Add("Plugin1 events:");
foreach (var ev in plugin1.GetType().GetEvents())
{
    string strName = ev.Name;
    string strType = ev.EventHandlerType.Name;
    MethodInfo strConnectedTo = ev.GetAddMethod();

    lbxInfo.Items.Add("Name = " + strName + " type =" + strType);

}

enter image description here

The part that I have not been able to do is to understand what events are connected to what. In short I would like to add a part that tells me what events are connected to what and what is instead not connected. Something like:

Plugin1 OnStatusChange1_Out connectedTo plugin2.PluginAction OnStatusChange1_Out connectedTo NULL

and this obviously has to be do through reflection and in the same foreach loop above.

Thank you in advance for any help Patrick





Aucun commentaire:

Enregistrer un commentaire