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,姓,名字,电子邮件
答案 0 :(得分:9)
也许这个?
// 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;
}
答案 1 :(得分:1)
不确定是否有更快的方法,但首先,获取您继承的基本类型的类型。
typeof(Client).BaseType
之后,您只能使用bindingflags获取基本属性。
BindingFlags.DeclaredOnly
之后对Client类型执行相同操作,并附加结果。
答案 2 :(得分:1)
我更喜欢基于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));
答案 3 :(得分:0)
怎么样:
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);