How to get the fieldInfo for a Friend WithEvents member?

621 Views Asked by At

I have the following member defined in a vb.net Form, MyForm:

Friend WithEvents myTab As Tab

I am trying to get this member using the following code:

Dim FieldInfo As System.Reflection.FieldInfo = MyForm.GetType.GetField("myTab", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)

, but I am always getting Nothing in return. If I try:

Dim MemberInfo As System.Reflection.MemberInfo = MyForm.GetType.GetMember("myTab", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)(0)

, I do get the member but I cannot get its value.

Are there other BindingFlags that need to be used to get the FieldInfo of a member with the Friend WithEvents modifier?

1

There are 1 best solutions below

0
On BEST ANSWER

Yes, this can't work as written. The VB compiler gives a WithEvents member special treatment to implement its feature. After it is done, your myTab variable is not a field anymore. Something you can see when you look at the generated assembly with the ildasm.exe utility. You'll see:

  • myTab is now a property with a getter and setter. You'd need to use GetProperty() instead of GetField() to retrieve it.
  • The property has a backing variable that stores the object reference, its name is _myTab. Note the leading underscore.

Not sure which way you actually want to go, you need the property if you want to tinker with events. So it is either one of these you need:

Dim info = MyForm.GetType().GetField("_myTab", _
               BindingFlags.Instance Or BindingFlags.NonPublic)

Or

Dim info = myForm.GetType().GetProperty("myTab", _
               BindingFlags.Instance Or BindingFlags.NonPublic)

Probably the first one.