加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用反射按顺序获取类的属性

发布时间:2020-12-15 23:42:31 所属栏目:百科 来源:网络整理
导读:请参考此代码 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; }............} 我需要通过order的orderAttribute按顺序获取类的
请参考此代码

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

}

我需要通过order的orderAttribute按顺序获取类的所有属性.我试过这个代码

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”属性.

如何处理这种情况?我需要订购所有属性,即使某些属性没有order属性的值.

解决方法

您在FirstOrDefault运算符上缺少方括号().此外,您应该在返回默认值时处理大小写.我建议在获得第一个或默认值之前选择Order值.对于没有DisplayAttribute的所有属性,它将返回0:

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

如果您希望没有DisplayAttribute的属性为last,则可以提供Int32.MaxValue作为要返回的默认值:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读