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

标签 c# linq c#-4.0 reflection

请引用这段代码

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/

相关文章:

c# - 我应该如何比较两个列表中的值?

c# - 有没有办法告诉 Resharper 6 忽略新的异步语言功能?

c#-4.0 - 从 C# 中的对象列表中搜索对象的有效方法

c# - dotnet pack 命令和 nuspec 文件不包括项目的 DLL

c# - 在 WPF 中创建自定义安装程序

c# - 遍历 NHibernate 实体的 IQueryable 时出现消息 "plan b"的 Antlr 异常

c# - ElasticSearch在多个字段上完全匹配

c#-4.0 - C# 泛型错误 : The constraints for type parameter 'T' of method . ..?

c# - ZedGraph,鼠标按下x轴时记录位置,C#

c# - 如何从cname中识别原始域名