Visualizzazione post con etichetta Reflection. Mostra tutti i post
Visualizzazione post con etichetta Reflection. Mostra tutti i post

28 marzo 2009

VB.NET : Copiare automaticamente le proprietà di un oggetto in un altro grazie alla Reflection

L’extension method che voglio postare questa volta consente di copiare le proprietà (almeno in lettura) di un oggetto sorgente, nelle proprietà (dello stesso tipo, con lo stesso nome e, almeno, in scrittura) di un altro oggetto:

<Extension()> _
Public Sub CopyFrom(ByVal destObj As Object, _
                   
ByVal sourceObj As Object)
    Dim sourceType = sourceObj.GetType()
    Dim destType = destObj.GetType()
    Dim sourceProperties = (From p In sourceType.GetProperties() _
                            Where p.CanRead _
                            Select p).ToList()
    For Each sourceProp In sourceProperties
        Dim propName = sourceProp.Name
        Dim destProp = destType.GetProperty(propName)
        If destProp IsNot Nothing AndAlso destProp.CanWrite Then
            If sourceProp.GetType().Equals(destProp.GetType()) Then
                Dim propValue = sourceProp.GetValue(sourceObj, Nothing)
                Try
                    destProp.SetValue(destObj, propValue, Nothing)
                Catch ex As Exception
               
End Try
            End If
        End If
    Next
End Sub

Utilizzando questo moetodo possiamo scrivere:

.
.
Dim destObj as Object
destObj.CopyFrom(sourceObj)
.
.

in modo da copiare tutte le proprietà di sourceObj nelle proprietà comuni di destObj.

28 aprile 2008

VB.NET : Recuperare il valore o il tipo di una proprietà in maniera ricorsiva tramite reflection.


Le due funzioni che vi propongo consentono di recuperare, in maniera ricorsiva, il valore o il tipo di una proprietà (pubblica) di un oggetto.

La proprietà può essere anche una delle proprietà di un oggetto aggregato all'oggetto di partenza, ad esempio:

dim fInfo as new FileInfo("c:\prova.txt")
dim value as object = getPropertyValue(fInfo,"Directory.LastAccessTime.Day")

recupera la proprietà Day (Integer) della proprietà LastAccessTime (di tipo DateTime) contenuta nella proprietà Directory (di tipo DirectoryInfo) dell'oggetto fInfo.


E' possibile indicare l'indice dell'oggetto da recuperare nel caso delle proprietà indicizzate (array, collection, etc., etc.).


In maniera analoga lavora la funzione che recupera il tipo della proprietà.

Imports System.Reflection
Public
Shared Function GetPropertyType(ByVal objType As Type, _
ByVal propertyName As String) As Type
Dim retval As Object = Nothing
Dim strArray = propertyName.Split(".")
If strArray.Count > 0 Then
Dim propinfo As PropertyInfo = objType.GetProperty(strArray(0))
If Not propinfo Is Nothing Then
If strArray.Count > 1 Then
Dim dotIndex = propertyName.IndexOf(".")
Dim propName = propertyName.Substring(IIf(dotIndex >= 0, dotIndex + 1, 0))
retval = GetPropertyType(propinfo.PropertyType, propName)
Else
retval = propinfo.PropertyType
End If
Else
Throw New Exception("Property name error!!!")
End If
Else
retval = objType
End If
Return retval
End Function

Public Shared Function GetPropertyValue(ByVal obj As Object, _
ByVal propertyName As String, _
Optional ByVal index As Integer = -1) As Object
Dim retval As Object = Nothing
Dim strArray = propertyName.Split(".")
If strArray.Count > 0 Then
Dim objType As Type = obj.GetType()
Dim propinfo As PropertyInfo = objType.GetProperty(strArray(0))
If Not propinfo Is Nothing Then
If strArray.Count > 1 Then
Dim dotIndex = propertyName.IndexOf(".")
Dim propName = propertyName.Substring(IIf(dotIndex >= 0, dotIndex + 1, 0))
retval = GetPropertyValue(propinfo.GetValue(obj, Nothing), propName, index)
Else
If index >= 0 Then
Dim indexes As Object()
ReDim indexes(0)
indexes(0) = index
retval = propinfo.GetValue(obj, indexes)
Else
retval = propinfo.GetValue(obj, Nothing)
End If
End If
Else
Throw New Exception("Property name error!!!")
End If
Else
retval = obj
End If
Return retval
End Function
 

20 aprile 2007

VB.NET : Determinare se un oggetto ha una determinata proprietà

La seguente funzione consente di sapere se un oggetto obj, passato come argomento, dispone di una proprietà chiamata propertyName eventualmente del tipo propertyType:


Public Function ObjectHasProperty(ByVal obj As Object, ByVal propertyName As String, Optional ByVal propertyType As Type = Nothing) As Boolean
  Dim retVal As Boolean = False
  Dim objType As Type = obj.GetType()
  Dim propinfo As System.Reflection.PropertyInfo = objType.GetProperty(propertyName)
  If Not propinfo Is Nothing Then
    If propertyType Is Nothing Or propinfo.PropertyType.IsAssignableFrom(propertyType) Then
      retVal = True
    End If
  End If
  Return retVal
End Function

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