I’m trying to serialize properties of a class that inherits from another using Reflection, but I would like to serialize only the properties of the child class, not the parent ones. How can I do that?
This is what I’m doing, and unfortunately it is getting all properties of the parent class too, as one would expect:
Public Function SaveData() As System.Collections.Generic.List(Of System.Xml.Linq.XElement) Implements Interfaces.ICustomXMLSerialization.SaveData
Dim elements As New List(Of System.Xml.Linq.XElement)
Dim ci As CultureInfo = CultureInfo.InvariantCulture
With elements
Dim props As PropertyInfo() = Me.GetType.GetProperties()
For Each prop As PropertyInfo In props
If TypeOf Me.GetType.GetProperty(prop.Name).PropertyType Is IList Then
.Add(New XElement(prop.Name, DWSIM.App.ArrayToString(Me.GetType.GetProperty(prop.Name).GetValue(Me, Nothing), ci)))
ElseIf TypeOf Me.GetType.GetProperty(prop.Name).GetValue(Me, Nothing) Is Double Then
.Add(New XElement(prop.Name, Double.Parse(Me.GetType.GetProperty(prop.Name).GetValue(Me, Nothing)).ToString(ci)))
Else
.Add(New XElement(prop.Name, Me.GetType.GetProperty(prop.Name).GetValue(Me, Nothing)))
End If
Next
End With
Return elements
End Function
Thanks in advance,
Daniel
You need to specify
BindingFlags.DeclaredOnlyas a parameter to yourGetPropertiescall.There are often gotchas around the use of these flags, though, so it may take some experimenting to find the exact combination of flags you need. The MSDN description of the enum is here.