gpt4 book ai didi

c# - 如何使用反射在派生类的属性之前获取基类的属性

转载 作者:太空狗 更新时间:2023-10-29 22:22:43 25 4
gpt4 key购买 nike

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();

This will list the properties in this order: Surname, FirstName, email, ID

Want the properties to display in this order: ID, Surname, FirstName, email

最佳答案

也许是这个?

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

关于c# - 如何使用反射在派生类的属性之前获取基类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19995955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com