1

我有某些类都继承自其他类。每个类,只继承自另一个类,从不继承两个类。我还有一个基类,它是我的继承树的“顶部”。类例如:

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 的属性并遍历它们时,我按以下顺序获取它们:

  1. 预定义类型
  2. 对象放置
  3. 表示
  4. 对象类型
  5. 全球标识
  6. 所有者历史
  7. 姓名
  8. 描述
  9. _ID

但是我需要这些属性按“从上到下”的顺序,所以:

  1. _ID
  2. 全球标识
  3. 所有者历史
  4. 姓名
  5. 描述
  6. 对象类型
  7. 对象放置
  8. 表示
  9. 预定义类型

因此,我想在每个类中实现一个方法,您可以调用该方法并以正确的顺序对属性进行排序。到目前为止,该方法看起来像这样:

        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;
            }
        }

有谁知道如何访问父对象而不仅仅是我在当前代码中所做的父类型?还有其他建议如何解决这个问题吗?

4

1 回答 1

1

你能试试这个。这将是满足您要求的更好解决方案

            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();
于 2017-07-07T06:50:35.873 回答