【问题标题】:Is it possible sort a type's properties returned from Type.GetProperties() using attributes?是否可以使用属性对从 Type.GetProperties() 返回的类型的属性进行排序?
【发布时间】:2013-03-20 21:19:56
【问题描述】:

根据MSDN

Type.GetProperties() GetProperties 方法不按特定顺序(如字母顺序或声明顺序)返回属性。您的代码不得依赖于返回属性的顺序,因为该顺序会有所不同。

是否可以以某种方式对属性进行注释(可能是自定义属性),以便您可以执行此类操作?

var properties = typeof(myClass).GetProperties()
.AsEnumerable().OrderBy(Func<VoodooOrdinalAttribute>);

public class MyClass
{
   [VoodooOrdinalAttribute(2)] public string Color { get; set;}
   [VoodooOrdinalAttribute(3)] public string Shape { get; set;}
   [VoodooOrdinalAttribute(1)] public string Mass { get; set;}
}

还有这个

public class VoodooOrdinalAttribute : Attribute
{
   public VoodooOrdinalAttribute(int ordinal)
   {
       this.Ordinal = ordinal;
   }
   public int Ordinal { get; set; }
}

并且期望属性的顺序是

  1. 质量
  2. 颜色
  3. 形状

【问题讨论】:

    标签: c# reflection types custom-attributes


    【解决方案1】:

    是的,您可以使用属性对属性进行排序。如果您像在示例中那样使用 use 定义属性,那么这里有一个 LINQ 查询,它按属性中指定的数字对具有该属性的属性进行排序。

    var propertyData = from prop in typeof(MyClass).GetProperties()
                       let voodooOrdinalAttribute = Attribute.GetCustomAttribute(prop, typeof(VoodooOrdinalAttribute)) as VoodooOrdinalAttribute
                       where voodooOrdinalAttribute != null
                       let lineOrder = voodooOrdinalAttribute.Ordinal
                       orderby lineOrder ascending
                       select prop;
    

    【讨论】:

    • 我已经编辑了我的问题以包含 VoodooOrdinalAttribute 实现。您的查询如何按照属性构造函数参数和/或属性指定的顺序进行?
    • 对于每个属性,它都会获取属性(第一个 let 表达式)。然后它进行空检查(where 子句),然后从属性的属性实例中获取序数(第二个 let 表达式)。最后,它按升序对属性进行排序(orderby 子句),然后选择属性(select 子句)。
    • 啊……明白了。 .Ordinal 是您在属性上赋予属性的名称。我会更新我的问题。干得好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    相关资源
    最近更新 更多