Here is a quick example of how one can use reflection to perform an upcast in vb.net.
In the sample code below, you have a person class and a contact class. The contact class inherits from the person class. Additionally, you have an instance of the Person class which needs to be converted to an instance of the Contact class. The below code can be used to perform this conversion.
This may not be the best way to do this, but it is certainly an easy and quick way of performing the task.
- Module Module1
- Sub Main()
- Dim p As New Person() With {.First = "Test", .Last = "User"}
- Console.WriteLine("{0} {1} {2}", p.GetType.FullName, p.First, p.Last)
- Dim c As Contact = Upcast(Of Person, Contact)(p)
- c.Phone = "555-123-4567"
- Console.WriteLine("{0} {1} {2} {3}", c.GetType.FullName, c.First, c.Last, c.Phone)
- c.CallContact()
- Console.ReadLine()
- End Sub
- Public Function Upcast(Of B, S As {New, B})(ByVal baseObj As B) As S
- Dim superObj As S = New S()
- Dim superProp As System.Reflection.PropertyInfo = Nothing
- For Each baseProp As System.Reflection.PropertyInfo In baseObj.GetType().GetProperties()
- superProp = superObj.GetType().GetProperty(baseProp.Name)
- superProp.SetValue(superObj, baseProp.GetValue(baseObj, Nothing), Nothing)
- Next
- Return superObj
- End Function
- Public Class Person
- Private _First As String
- Private _Last As String
- Public Property First() As String
- Get
- Return _First
- End Get
- Set(ByVal value As String)
- _First = value
- End Set
- End Property
- Public Property Last() As String
- Get
- Return _Last
- End Get
- Set(ByVal value As String)
- _Last = value
- End Set
- End Property
- End Class
- Public Class Contact
- Inherits Person
- Private _Phone As String
- Public Property Phone() As String
- Get
- Return _Phone
- End Get
- Set(ByVal value As String)
- _Phone = value
- End Set
- End Property
- Public Sub CallContact()
- Console.WriteLine("Calling {0}....", Phone)
- End Sub
- End Class
- End Module
0 comments:
Post a Comment