[英]c# how to get list of derived class properties by reflection, ordered by base class properties first, and then derived class props
[英]How to use reflection to get properties of a base class before properties of the derived class
public class BaseDto
{
public int ID{ get; set; }
}
public class Client: BaseDto
{
public string Surname { get; set; }
public string FirstName{ get; set; }
public string email{ get; set; }
}
PropertyInfo[] props = typeof(Client).GetProperties();
这将按以下顺序列出属性:姓氏,名字,电子邮件,ID
希望按以下顺序显示属性:ID,姓氏,名字,电子邮件
也许这个?
// this is alternative for typeof(T).GetProperties()
// that returns base class properties before inherited class properties
protected PropertyInfo[] GetBasePropertiesFirst(Type type)
{
var orderList = new List<Type>();
var iteratingType = type;
do
{
orderList.Insert(0, iteratingType);
iteratingType = iteratingType.BaseType;
} while (iteratingType != null);
var props = type.GetProperties()
.OrderBy(x => orderList.IndexOf(x.DeclaringType))
.ToArray();
return props;
}
不确定是否有更快的方法,但首先,获取您继承的基本类型的类型。
typeof(Client).BaseType
之后,您只能使用bindingflags获取基本属性。
BindingFlags.DeclaredOnly
之后,对Client类型执行相同操作,并附加结果。
我更喜欢基于linq的解决方案:
var baseProps = typeof(BaseDto).GetProperties();
var props = typeof(Client).GetProperties();
var allProps = baseProps
.Concat(props.Where(p => baseProps
.Select(b => b.Name)
.Contains(p.Name) == false));
关于什么:
Dictionary<string, PropertyInfo> _PropertyIndex = new Dictionary<string, PropertyInfo>();
Type thisType = typeof(Client);
foreach (PropertyInfo pi in thisType.BaseType.GetProperties())
_PropertyIndex.Add(pi.Name.ToUpper(), pi);
foreach (PropertyInfo pi in thisType.GetProperties())
if( !_PropertyIndex.ContainsKey(pi.Name.ToUpper()))
_PropertyIndex.Add(pi.Name.ToUpper(), pi);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.