【问题标题】:Dynamically declaring and instantiating objects based on a parameter基于参数动态声明和实例化对象
【发布时间】:2018-03-13 16:30:12
【问题描述】:

是否可以在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

【问题讨论】:

  • 你到底想做什么?
  • 在“Denamicly Declaring”之前,您将如何准确地在代码中引用一个不存在的对象?
  • 这只是问题的一个模型,但我有一个表单类,我希望通过发送选择案例语句的结果来声明和实例化它。这些参数包含每个表单的所有信息——表单名称(用于对 UI 进行轻微修改)和数据,也用于 UI

标签: vb.net declaration instantiation


【解决方案1】:

使用反射,这样的事情可能会满足您的需求。我还没有测试过,但它应该可以工作。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 2019-12-10
    • 2014-01-26
    • 1970-01-01
    相关资源
    最近更新 更多