Reputation: 63
I have certain classes that all inherit from other classes. Each class, only inherits from one other class, never two classes. I've also got a Base-Class that is the "top" of my inheritance tree. Classes are for example:
public class IfcAlignment : IfcLinearPositioningElement
{
public IfcAlignmentTypeEnum PredefinedType {get; set;}
}
public class IfcLinearPositioningElement : IfcProduct
{
public IfcCurve Axis {get; set;}
}
public class IfcProduct : IfcObject
{
public IfcObjectPlacement ObjectPlacement {get; set;}
public IfcProductRepresentation Representation {get; set;}
}
public class IfcObject: IfcRoot
{
IfcLabel ObjectType {get; set;}
}
public class IfcRoot : IfcBase
{
public IfcGloballyUniqueId GlobalId {get; set;}
public IfcOwnerHistory OwnerHistory {get; set;}
public IfcLabel Name {get; set;}
public IfcText Description {get; set;}
}
public abstract class IfcBase
{
public int _ID {get; set;}
}
This is one set of inheritance within my structure. When I now call the properties of IfcAlignment and loop through them, I get them in this order:
However I need these properties in the order "top-to-bottom" so:
Therfore I wanted to implement a method in every class, that you can call and that would sort the properties in the correct order. the method looks like this so far:
override public List<PropertyInfo> SortMyProperties(object entity)
{
List<PropertyInfo> returnValue = new List<PropertyInfo>();
if (entity is IfcBase && !entity.GetType().Name.Contains("IfcBase"))
{
//Here I need to get the actual parent object:
// I tried the following, which did no work unfortunately:
// var parent = entity.GetType().BaseType;
PropertyInfo propInfo = parent.SortMyProperties(parent);
//get my own properties:
Type type = entity.GetType();
var genuineProps = typeof(/*type of the current class*/).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (var prop in genuineProps)
{
returnValue.Add(prop);
}
return returnValue;
}
else
{
var properties = this.GetType().GetProperties();
foreach (var prop in properties)
{
returnValue.Add(prop);
}
return returnValue;
}
}
Does anyone have an idea how to access the parent oject and not just the parent type, which I'm doing in my current code? Are any other suggestions how to solve the problem?
Upvotes: 1
Views: 1598
Reputation: 905
Can you try this. This will be the better solution to achieve your requirement
var type = typeof(IfcAlignment);
List<string> PropertyNames= new List<string>();
while(type!=null)
{
var properties = type.GetProperties().Where(x => x.DeclaringType == type).Select(x=>x.Name).Reverse().ToList();
foreach(string name in properties)
{
PropertyNames.Add(name);
}
type = type.BaseType;
}
PropertyNames.Reverse();
Upvotes: 1