简体   繁体   中英

Getting all events of a Control in C#

I am trying to get all events information concerning a specific control.
For this purpose, I wrote a snippet of code that works if I hard code the class name, But when I try to make it dynamic it fails, That is it doesn't give any error, but instead, the events collection becomes null.
This is the code that works :

AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomain_ReflectionOnlyAssemblyResolve;

var assembly = System.Reflection.Assembly.ReflectionOnlyLoadFrom(typeof(DataGridView).Module.FullyQualifiedName);
var events = Type.ReflectionOnlyGetType(typeof(DataGridView).AssemblyQualifiedName, false, true).GetEvents();

And this is the counter part that fails:

AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomain_ReflectionOnlyAssemblyResolve;
var assembly = System.Reflection.Assembly.ReflectionOnlyLoadFrom(cmbox.SelectedItem.GetType().Module.FullyQualifiedName);
var events = Type.ReflectionOnlyGetType(cmbox.SelectedItem.GetType().AssemblyQualifiedName, false, true).GetEvents();

this ComboBx is filled with windows form controls like this :

var controlType = typeof(Control);
            var controls = controlType
                .Assembly
                .GetTypes()
                .Where(t => controlType.IsAssignableFrom(t) &&
                            t.Namespace == "System.Windows.Forms"
                );
            foreach (var control in controls)
            {
                cmbox.Items.Add(control);
            }

And by the way this is the event handlers content :

Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
{
      return System.Reflection.Assembly.ReflectionOnlyLoad(args.Name);  
}

So what am I missing here? how to get around this ?

When you call

var events = Type.ReflectionOnlyGetType(cmbox.SelectedItem.GetType().AssemblyQualifiedName, 
             false, true).GetEvents();

it returns System.RuntimeType

whereas when you explictly call typeof(DataGridView) it generates it's full assembly qualified name.

One workaround I found is by using dynamic keyword

here it is

        dynamic controltype = cmbx.SelectedItem;
        var events = Type.ReflectionOnlyGetType(controltype.AssemblyQualifiedName, false, true).GetEvents();
        foreach (var item in events)
        {

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM