开发者

NewLateBinding.LateSet to reflection call

开发者 https://www.devze.com 2022-12-19 06:12 出处:网络
Assume I have an Excel.PivotField, and I need to setHiddenItemsList on my object. With VB.NET and Option Strict Off & Option Explicit Off this would result in:

Assume I have an Excel.PivotField, and I need to setHiddenItemsList on my object.

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

Dim field as Excel.PivotField = MyFunctionCall()

field.HiddenItemsList = GetHiddenItems()

While this works with this security setting, it obviously doesn't work when you set Option Strict On and Option Explicit On.

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

But when using late binding, it works perfectly.

Now the next step i开发者_如何学Cs 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)

Easy right?

But this code relies on the Microsoft.VisualBasic namespace. And ofcourse, we don't want that.

So I tried converting it to a plain Reflection call:

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

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

And help? ;-)


Always nice to answer your own question.

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

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

Here's the answer for other SO-ers :D

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

Cheers

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号