Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '------------------------------------------------------------------------------
- ' Crear un objeto a partir de una cadena con Activator (05/Ene/13)
- '
- ' El artículo explicativo está en:
- ' http://www.elguillemola.com/index.php/2013/01/crear-un-objeto-a-partir-de-una-cadena-con-activator-createinstance/
- '
- ' ©Guillermo 'guille' Som, 2013
- '------------------------------------------------------------------------------
- Namespace ActivatorVB
- Public NotInheritable Class CrearClase
- Public Shared Sub Main()
- Main2()
- ' La clase a crear
- Dim elNombre = "ActivatorVB.Colega"
- crearColega(elNombre)
- ' Esta clase se llama igual,
- ' pero no es del mismo tipo
- ' y no pasaría la prueba de IsAssignableFrom,
- ' aunque no daría error al hacer la conversión
- ' pero no crearía una instancia,
- ' por tanto Activator devolvería nulo,
- ' en realidad el valor nulo lo devuelve
- ' la operación de conversión de tipos
- ' por eso en VB utilizo TryCast en lugar
- ' de DirectCast o CType
- elNombre = "OtroEspacio.Colega"
- crearColega(elNombre)
- ' esta clase se basa en la que queremos crear
- ' aunque esté en otro espacio de nombres
- elNombre = "OtroEspacio.Coleguilla"
- crearColega(elNombre)
- '' Esta no tiene constructor
- 'elNombre = "OtroEspacio.Coleguilla2"
- 'crearColega(elNombre)
- ' este tipo no existe,
- ' pero debemos usar IsAssignableFrom
- ' para no provocar una excepción
- elNombre = "Activator.Colega"
- crearColega(elNombre)
- ' esta se basa en la nuestra
- ' pero es abstracta (no tiene constructor)
- ' ya dará un error al crearla
- ' aunque pasaría la prueba de IsAssignableFrom
- Try
- elNombre = "ActivatorVB.ColegaAbstracto"
- crearColega(elNombre)
- Catch ex As Exception
- Console.WriteLine("Mrw! (o Ups!) esta clase {0} da error: {1}",
- elNombre, ex.Message)
- End Try
- Console.ReadKey()
- End Sub
- Private Shared Sub crearColega(laClase As String)
- Dim elTipo As Type = Type.GetType(laClase)
- If Not GetType(Colega).IsAssignableFrom(elTipo) Then
- Console.WriteLine("El tipo: {0} no es del tipo adecuado." & vbLf & "",
- laClase)
- Return
- End If
- 'Dim obj1 As Object = Activator.CreateInstance(elTipo)
- 'Dim obj2 As Colega = CType(Activator.CreateInstance(elTipo), Colega)
- 'Dim obj3 As Colega = DirectCast(Activator.CreateInstance(elTipo), Colega)
- Dim obj As Colega = TryCast(Activator.CreateInstance(elTipo), Colega)
- If obj IsNot Nothing Then
- obj.Nombre = "Pepe"
- obj.Email = "pepe@outlook.com"
- Console.WriteLine("Objeto creado correctamente: {0}{1}{2}, {3}",
- obj.GetType().Name, vbCrLf,
- obj.Nombre, obj.Email)
- Else
- Console.WriteLine("Parece que el tipo: {0} no es del tipo adecuado.",
- laClase)
- End If
- Console.WriteLine()
- End Sub
- Sub pruebaDirecta()
- Dim laClase = "ActivatorVB.Colega"
- Dim elTipo As Type = Type.GetType(laClase)
- Dim obj As Colega = TryCast(Activator.CreateInstance(elTipo), Colega)
- If obj IsNot Nothing Then
- obj.Nombre = "Pepe"
- obj.Email = "pepe@outlook.com"
- End If
- End Sub
- Shared Sub Main2()
- Dim laClase = "ActivatorVB.unColega"
- Dim elTipo As Type = Type.GetType(laClase)
- Dim obj As IColega = TryCast(Activator.CreateInstance(elTipo), IColega)
- If obj IsNot Nothing Then
- obj.Nombre = "Pepe"
- End If
- End Sub
- End Class
- Public Interface IColega
- Property Nombre As String
- End Interface
- Public Class unColega
- Implements IColega
- Public Property Nombre As String Implements IColega.Nombre
- End Class
- Public Class Colega
- Public Property Nombre As String
- Public Property Email As String
- End Class
- ' Clase no instanciable
- Public MustInherit Class ColegaAbstracto
- Inherits Colega
- Public Property Edad As Integer
- End Class
- End Namespace
- Namespace OtroEspacio
- Public Class Colega
- Public Property Nombre As String
- Public Property Edad As Integer
- End Class
- Public Class Coleguilla
- Inherits ActivatorVB.Colega
- Public Property Edad As Integer
- End Class
- ' las clase selladas (sealed / NotInheritable)
- ' se pueden usar, pero siempre deben tener
- ' un constructor público sin parámetros
- Public NotInheritable Class Coleguilla2
- Inherits ActivatorVB.Colega
- 'Protected Sub New()
- 'End Sub
- 'Private Sub New()
- 'End Sub
- Public Property Edad As Integer
- End Class
- End Namespace
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement