是否可以根据VB.net中的参数动态声明和实例化对象?
我必须声明我希望实例化的每个对象,这似乎很疯狂。
下面的代码不起作用,但也许有某种解决方法可以达到相同的效果?
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim jeff As String = "Jeff"
DynamicDeclare(jeff)
End Sub
Private Sub DynamicDeclare(ByVal objectName As String)
Dim objectName As New Person
End Sub
End Class
Class Person
Property FirstName As String
Property Age As Integer
End Class
答案 0 :(得分:0)
使用反射,这样的东西可能适合您的需要。我没有测试过,但它应该可以工作。
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim jeff As String = "Jeff"
Dim methodName as string = "DynamicDeclare"
Dim type as Type = GetType(Person)
Dim method as System.Reflection.MethodInfo = type.GetMethod(methodName)
Dim person as Person = method.Invoke(Nothing, new object(){jeff})
End Sub
End Class
Public Class Person
Property FirstName As String
Property Age As Integer
Public Function DynamicDeclare(ByVal objectName As String) as Person
Dim person As New Person
person.FirstName = objectName
Return person
End Function
End Class