Can I pass a class reference as a function parameter in VBNet?

Please forgive me if I use the wrong terminology or sound like a complete noob.

When calling sub in the class library, I would like to pass not an instance form, but just a reference to the class representing the form. Then I want to create an instance of the form from the class library function. Is it possible?

Something like the following:

In the main application:

ClassLib.MyClass.DisplayForm(GetType(Form1)) 

Then in the class library

 Public Class MyClass Public Shared Sub DisplayForm(WhichFormClass As Type) Dim MyForm as Form = WhichFormClass.CreateObject() 'Getting imaginitive MyForm.ShowDialog() End Sub End Class 

I hope my example conveys what I'm trying to accomplish. If you think my approach is fictitious, I am open to alternative strategies.

+4
source share
2 answers

In addition to MotoSV's answer, here is a version that uses only generics:

 Public Shared Sub DisplayForm(Of T As {New, Form})() Dim instance = New T() instance.ShowDialog() End Sub 

What you can use as:

 DisplayForm(Of Form1)() 

With this approach, you can be sure that the passed type is a form and that the instance has the ShowDialog() method. There is no need for admission, which may end in failure. However, to call a method, you must know the type parameter at design time.

+5
source

Try

 Dim classType As Type = GetType(Form1) 

Then call the method:

 DisplayForm(classType) 

Then you can use the information and reflection of this type to instantiate the runtime in the DisplayForm method:

 Activator.CreateInstance(classType) 

Please note that this is a simple example and does not perform error checking, etc. You should read a little more about reflection to make sure that you are dealing with any potential problems.

Change 1:

A simple example:

 Public Class MyClass Public Shared Sub DisplayForm(ByVal formType As Type) Dim form As Form = DirectCast(Activator.CreateInstance(formType), Form) form.ShowDialog() End Sub End Class 

You use a method like:

 Dim formType As Type = GetType(Form1) MyClass.DisplayForm(formType) 

Again, it is best to do some error checking in all of this.

+3
source

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


All Articles