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

编程入门 行业动态 更新时间:2024-10-26 00:23:27
本文介绍了使用反射按顺序获取类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

请参考此代码

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

更多推荐

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

本文发布于:2023-11-12 11:40:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581403.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:反射   顺序   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!