我有某些类都继承自其他类。每个类,只继承自另一个类,从不继承两个类。我还有一个基类,它是我的继承树的“顶部”。类例如:
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;}
}
这是我的结构中的一组继承。当我现在调用 IfcAlignment 的属性并遍历它们时,我按以下顺序获取它们:
- 预定义类型
- 轴
- 对象放置
- 表示
- 对象类型
- 全球标识
- 所有者历史
- 姓名
- 描述
- _ID
但是我需要这些属性按“从上到下”的顺序,所以:
- _ID
- 全球标识
- 所有者历史
- 姓名
- 描述
- 对象类型
- 对象放置
- 表示
- 轴
- 预定义类型
因此,我想在每个类中实现一个方法,您可以调用该方法并以正确的顺序对属性进行排序。到目前为止,该方法看起来像这样:
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;
}
}
有谁知道如何访问父对象而不仅仅是我在当前代码中所做的父类型?还有其他建议如何解决这个问题吗?