Obtaining reference to Class instance by string name - VB.NET

前端 未结 1 1665
梦谈多话
梦谈多话 2021-01-12 16:05

Is it possible using Reflection or some other method to obtain a reference to a specific class instance from the name of that class instance?

For example the framewo

相关标签:
1条回答
  • 2021-01-12 16:31

    I don´t know if I´ve understood you well, but my answer is yes, you can do it by reflection. You´ll need to import System.Reflection namespace.

    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, uou can get the value of your property, just like this:

    MyProperty.GetValue(MyInstance, Nothing)
    

    Passing to the method the instace of what you want to know the value.

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

    EDIT

    This would 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
    
    0 讨论(0)
提交回复
热议问题