Recuperare le proprietà di una classe ed il loro valore

Scritto da  Massimiliano Bellisario il domenica 31 ottobre 2010  •  Linguaggio: C#,VB   • Livello: 200


In questo esempio viene descritto il codice per recuperare le proprietà di una classe ed il loro valore.

C#

public class Persona
{
public string Nome{ get; set; }
public string Cognome{ get; set; }

public Persona() {}
}

public void Test()
{
var persona=new Persona
{
Nome="Massimiliano", Cognome="Bellisario"
};
var type = typeof(Persona);
var properties = type.GetProperties();

foreach (PropertyInfo property in properties)
{
Console.Writeln("{0} : {1}", property.Name, property.GetValue(persona, null));
}
}

 

VB.NET

Public Class Persona
Public Property Nome() As String
Get
Return m_Nome
End Get
Set
m_Nome = Value
End Set
End Property
Private m_Nome As String

Public Property Cognome() As String
Get
Return m_Cognome
End Get
Set
m_Cognome = Value
End Set
End Property
Private m_Cognome As String

Public Sub New()
End Sub
End Class

Public Sub Test()
Dim persona = New Persona() With { _
.Nome = "Massimiliano", _
.Cognome = "Bellisario" _
}

Dim type = GetType(Persona)
Dim properties = type.GetProperties()

For Each [property] As PropertyInfo In properties
Console.Writeln("{0} : {1}", [property].Name, [property].GetValue(persona, Nothing))
Next
End Sub

 

Il codice non riesce a recuperare le proprietà indicizzate.


Tags: VB.NET,C#

 
x