NewLateBinding.LateSet to call reflection

Suppose I have Excel.PivotField and I need to set the HiddenItemsList on my object.

With VB.NET and Option Strict Off and Option Explicit Off this will result in:

Dim field as Excel.PivotField = MyFunctionCall()
field.HiddenItemsList = GetHiddenItems()

Although this works with this security setting, it obviously does not work if you set Option Strict On and Option Explicit On .

The IDE cannot resolve the HiddenItemsList property on my PivotField (first issue).

But when using late binding, it works great.

Now the next step is to enable Option Strict and Explicit (we are going to convert to C # in the future).

So, I look how the code is compiled:

NewLateBinding.LateSet(field , Nothing, "HiddenItemsList", New Object() { GetHiddenItems() }, Nothing, Nothing)
Is it easy?

But this code depends on the Microsoft.VisualBasic namespace. And, of course, we do not want this.

So I tried to convert it to a regular Reflection call:

GetType(Excel.PivotField).GetProperty("HiddenItemsList").SetValue(field , GetHiddenItems() , Reflection.BindingFlags.SetProperty, Nothing, Nothing, Nothing)

Unfortunately, the first part ( GetType(Excel.PivotField).GetProperty("HiddenItemsList") ) already returns Nothing , so I'm stuck there.

And help ?; -)

+4
source share
1 answer

It is always nice to answer your own question.

Since GetType(Excel.PivotField).GetProperty("HiddenItemsList") returns Nothing, we need another way.

There is a Type method, namely InvokeMember , and the method works with the correct properties!

Here is the answer for other SO servers: D

GetType(Excel.PivotField).InvokeMember("HiddenItemsList", Reflection.BindingFlags.SetProperty, Nothing, field, New Object() {GetHiddenItems() }, Nothing, Nothing, Nothing)

Greetings

+1
source

Source: https://habr.com/ru/post/1300587/


All Articles