sti*_*red 5 c# reflection base propertyinfo
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();
Run Code Online (Sandbox Code Playgroud)
这将按以下顺序列出属性:姓氏,名字,电子邮件,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;
}
Run Code Online (Sandbox Code Playgroud)
不确定是否有更快的方法来做到这一点,但首先,获取您继承的基类型的类型。
typeof(Client).BaseType
Run Code Online (Sandbox Code Playgroud)
之后,您可以使用绑定标志仅获取基本属性。
BindingFlags.DeclaredOnly
Run Code Online (Sandbox Code Playgroud)
之后对客户端类型执行相同的操作,并附加结果。