我有某些类都继承自其他类。每个类只继承自另一个类,从不继承两个类。 我还有一个Base-Class,它是我的继承树的“顶层”。 例如:类
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的属性并遍历它们时,我按顺序得到它们:
但是我需要按照“从上到下”的顺序使用这些属性,所以:
因此,我想在每个类中实现一个方法,您可以调用它,并按正确的顺序对属性进行排序。到目前为止,该方法看起来像这样:
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;
}
}
有没有人知道如何访问父对象而不仅仅是父类型,我正在使用当前代码?还有其他建议如何解决问题?
答案 0 :(得分:0)
你能试试吗?这将是实现您的要求的更好解决方案
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();