26 febbraio 2007

VB.NET: Creare oggetti in maniera dinamica.

La funzione che riporto in questo post permette di creare, in maniera dinamica, un qualsiasi oggetto di .NET a partire dal nome completo della classe (comprensivo di namespace) e dall'assembly in cui è contenuto:


Public Function CreaOggetto(ByVal FullClassName As String, ByVal AssemblyName As String) As Object
  Dim retObj As Object = Nothing
  Dim asm As System.Reflection.Assembly = _
   Assembly.LoadWithPartialName(AssemblyName)
  If Not asm Is Nothing Then
    Dim type As System.Type = asm.GetType(FullClassName)
    If Not type Is Nothing Then
      retObj = Activator.CreateInstance(type)
    End If
  End If
  Return retObj
End Function


Ad esempio la chiamata:
 CreaOggetto("System.Web.Ui.WebControls.Label","System.Web")
crea un oggetto Label

Nessun commento: