Getting reference to class instance by string name - VB.NET

Can I use Reflection or some other method to get a reference to a specific instance of a class from the name of this instance of the class?

For example, the infrastructure for applications that I actively use uses instances of a public class, such as: Public bMyreference as MyReference = new MyReference

Then, throughout the application, bMyReference is used by custom controls and code.

One of the properties of custom controls is the "Field Name", which refers to the property in these class instances (bMyReference.MyField) as a string.

What I would like to do is parse this line of "bMyReference.MyField" and then go back to the actual instance / property.

In VB6, I would use EVAL or something to simulate to convert the string to an actual object, but this obviously does not work in VB.net

What I imagine is something like this

Dim FieldName as String = MyControl.FieldName ' sets FielName to bMyReference.MyField Dim FieldObject() as String = FieldName.Split(".") ' Split into the Object / Property Dim myInstance as Object = ......... ' Obtain a reference to the Instance and set as myInstance Dim myProperty = myInstance.GetType().GetProperty(FieldObject(1)) 
+4
source share
1 answer

I don’t know if I understood you well, but my answer is yes, you can do this by reflecting. You need to import the System.Reflection .

Here is an example:

  ' Note that IΒ΄m in namespace ConsoleApplication1 Dim NameOfMyClass As String = "ConsoleApplication1.MyClassA" Dim NameOfMyPropertyInMyClass As String = "MyFieldInClassA" ' Note that you are getting a NEW instance of MyClassA Dim MyInstance As Object = Activator.CreateInstance(Type.GetType(NameOfMyClass)) ' A PropertyInfo object will give you access to the value of your desired field Dim MyProperty As PropertyInfo = MyInstance.GetType().GetProperty(NameOfMyPropertyInMyClass) 

Once you have MyProperty, you can get the value of your property like this:

 MyProperty.GetValue(MyInstance, Nothing) 

Passing to the method what you want to know.

Tell me, if this solves your question, please :-)

EDIT

It will be ClassA.vb

 Public Class MyClassA Private _myFieldInClassA As String Public Property MyFieldInClassA() As String Get Return _myFieldInClassA End Get Set(ByVal value As String) _myFieldInClassA = value End Set End Property End Class 
+6
source

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


All Articles