![](/img/trans.png)
[英]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.