c# - How to get events of type by reflection ignoring events on parent interfaces -


i have following code

type type = ... var events=type.getevents(     bindingflags.declaredonly      | bindingflags.instance      | bindingflags.public).tolist();  

however returning me events declared on parent interfaces. example

both

uielement contentelement 

implement

iinputelement 

which defines event

// // summary: //     occurs when mouse pointer moves while mouse pointer on element. event mouseeventhandler previewmousemove; 

but above call getevents binding flags set above returns event interface 2 concrete classes.

how can filter out events defined on parent interfaces getevents?

note generating extensions methods each event so

public static  iobservable<eventpattern<mousebuttoneventargs>>  previewmouseleftbuttondownobserver(this iinputelement this){         return observable                .fromeventpattern                <mousebuttoneventhandler, mousebuttoneventargs>                ( h => this.previewmouseleftbuttondown += h                , h => this.previewmouseleftbuttondown -= h); } 

so did root definition of event not derived virtual or interface implementations.

in example:

interface iface {     event eventhandler a; }  class base {     public virtual event eventhandler b;      public event eventhandler c; }  class yourtype : base, iface {     public event eventhandler a;          // implements interface      public override event eventhandler b; // overrides base class implementation      public event eventhandler d;          // new event } 

which event want see if use reflection on typeof(yourtype)?

answer:

you can use like:

events.where(x =>   x.getaddmethod().getbasedefinition().declaringtype == type   && !x.getaddmethod().isfinal)   ); 

where type in question. first criterion makes sure not event defined on parent type. second criterion makes sure it's not interface implementation. might not need second criterion, depending on exact setup.

edit answer

events.where(x =>{     var addmethod = x.getaddmethod();    var basetype = addmethod.getbasedefinition().declaringtype;    return basetype == type && (!addmethod.isfinal || basetype.isinterface); })  

this addition ensures interfaces well.

alternative approach:

to determine if member implements interface or not, 1 can use this:

var interfaceimplementingmethods = new hashset<methodinfo>(type.getinterfaces()   .selectmany(i => type.getinterfacemap(i).targetmethods)); var result = events.where(x => !interfaceimplementingmethods   .contains(x.getaddmethod())); 

it should work if implementing member declared virtual (or abstract). must combined getbasedefinition() if want exclude inherited members, of course.


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -