请引用这段代码
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 来获取类的所有属性。我试过用这段代码来做
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”属性。
遇到这种情况怎么办?我需要对所有属性进行排序,即使某些属性没有排序属性的值。
最佳答案
您在 FirstOrDefault
运算符上缺少方括号 ()
。您还应该处理返回默认 值的情况。我建议在获取第一个或默认值之前选择 Order
值。这将为所有没有 DisplayAttribute
的属性返回 0
:
var prop = typeof(A)
.GetProperties()
.OrderBy(p => p.GetCustomAttributes(typeof(DisplayAttribute), true)
.Cast<DisplayAttribute>()
.Select(a => a.Order)
.FirstOrDefault());
如果您希望没有 DisplayAttribute 的属性放在最后,您可以提供 Int32.MaxValue
作为要返回的默认值:
.Select(a => a.Order)
.DefaultIfEmpty(Int32.MaxValue)
.First()
关于c# - 使用反射按顺序获取类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22306689/