使用反射按顺序获取类的属性 [英] Get properties of class by order using reflection

查看:90
本文介绍了使用反射按顺序获取类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参考此代码

public class A : B
{
     [Display(Name = "Initial Score Code", Order =3)]
     public Code { get; set; }

     [Display(Name = "Initial Score Code", Order =2)]
     public Name{ get; set; }
............

}

我需要通过Display的orderAttribute通过order获取类的所有属性.我已经尝试过使用此代码来做

I need to get all properties of class through order by orderAttribute of Display. I have tried with this code to do

 var prop = typeof(A)
            .GetProperties()
            .OrderBy(p => ((DisplayAttribute)p.GetCustomAttributes(typeof(DisplayAttribute),  true).FirstOrDefault).Order);

但是会导致错误

对象引用不设置对象实例

object reference not to set an instance of object

由于某些属性在"DisplayAttribute"中不具有"Order"属性,因此我认为这是一个问题.

I assumed this issue because of some property not having "Order" property in "DisplayAttribute" .

如何处理这种情况?我需要对所有属性进行排序,即使某些属性不具有order属性的值.

How to handle this kind of situation? I need to order all the properties even though some property not having the value of order property.

推荐答案

您在 FirstOrDefault 运算符上缺少括号().还应该处理返回 default 值的情况.我建议在获取第一个或默认值之前选择 Order 值.对于所有没有 DisplayAttribute 的属性,这将返回 0 :

You are missing brackets () on FirstOrDefault operator. Also you should deal with case when default value is returned. I suggest to select Order value before getting first or default value. That will return 0 for all properties which don't have DisplayAttribute:

var prop = typeof(A)
    .GetProperties()
    .OrderBy(p => p.GetCustomAttributes(typeof(DisplayAttribute), true)
                   .Cast<DisplayAttribute>()
                   .Select(a => a.Order)
                   .FirstOrDefault());

如果希望不带DisplayAttribute的属性位于最后,则可以提供 Int32.MaxValue 作为要返回的默认值:

If you want properties without DisplayAttribute to be last, you can provide Int32.MaxValue as default value to be returned:

                   .Select(a => a.Order)
                   .DefaultIfEmpty(Int32.MaxValue)
                   .First()

这篇关于使用反射按顺序获取类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆