Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

Late binding when Option Strict is On

2009-06-05

Once you have an object, you can dynamically decide what method to call, or property to use, by calling the InvokeMember function of the object’s type. In this example, I call the ShowDialog method of the object. Note that object members (non static) must have target instance, in my case X.

Dim X As New Form1()
Dim T As Type = X.GetType()
T.InvokeMember(“ShowDialog”, Reflection.BindingFlags.InvokeMethod, Nothing, X, Nothing)

How you do things with COM objects that you don’t have a reference to, depends on if you are using Visual Basic in strict mode or not. If option strict is off, this code will actually run:

Dim X As Object = Microsoft.VisualBasic.Interaction.CreateObject(“ADODB.Connection”)
X.ConnectionString = “Hej”

If option strict is on, you will get an error telling you that you can’t do late binding when option strict is on. You can, you just have to do it through the InvokeMember function of the type.

Dim X As Object = Microsoft.VisualBasic.Interaction.CreateObject(“ADODB.Connection”)
Dim Args() As String = {“Hej”}
X.GetType().InvokeMember(“ConnectionString”, Reflection.BindingFlags.SetProperty, Nothing, X, Args)

With this, you can build programs that use for example Microsoft Word if it is installed, but still can run if it isn’t.

Categories: General

Tags: Late Binding

Leave a Reply

Your email address will not be published. Required fields are marked *



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips