http://www.ohchr.org。
Type.GetProperties
<>指出,其收复保证不按字母或申报顺序进行,尽管经过简单的测试显示,一般来说,其返还是按申报顺序进行的。 是否有具体假设,你知道情况并非如此? 除此之外,所建议的选择是什么?
详细版
我实现了Type.GetProperties。 国家:
The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which properties are returned, because that order varies.
so there is no guarantee that the collection returned by the method will be ordered any specific way. Based on some tests, I ve found to the contrary that the properties returned appear in the order they re defined in the type.
Example:
class Simple
{
public int FieldB { get; set; }
public string FieldA { get; set; }
public byte FieldC { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Simple Properties:");
foreach (var propInfo in typeof(Simple).GetProperties())
Console.WriteLine(" {0}", propInfo.Name);
}
}
产出:
Simple Properties:
FieldB
FieldA
FieldC
一种情况是,该类型有父母也有财产:
class Parent
{
public int ParentFieldB { get; set; }
public string ParentFieldA { get; set; }
public byte ParentFieldC { get; set; }
}
class Child : Parent
{
public int ChildFieldB { get; set; }
public string ChildFieldA { get; set; }
public byte ChildFieldC { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Parent Properties:");
foreach (var propInfo in typeof(Parent).GetProperties())
Console.WriteLine(" {0}", propInfo.Name);
Console.WriteLine("Child Properties:");
foreach (var propInfo in typeof(Child).GetProperties())
Console.WriteLine(" {0}", propInfo.Name);
}
}
产出:
Parent Properties:
ParentFieldB
ParentFieldA
ParentFieldC
Child Properties:
ChildFieldB
ChildFieldA
ChildFieldC
ParentFieldB
ParentFieldA
ParentFieldC
Which means the GetProperties
method walks up the inheritance chain from bottom up when discovering the properties. That s fine and can be handled as such.
问题:
- Are there specific situations where the described behavior would differ that I ve missed?
- If depending on the order is not recommended then what is the recommended approach?
一种似乎显而易见的解决办法是界定一种习俗特性,表明其特性(should)的顺序(与>Order
上的不动产(的属性)。 类似:
public class PropOrderAttribute : Attribute
{
public int SeqNbr { get; set; }
}
其后实施:
class Simple
{
[PropOrder(SeqNbr = 0)]
public int FieldB { get; set; }
[PropOrder(SeqNbr = 1)]
public string FieldA { get; set; }
[PropOrder(SeqNbr = 2)]
public byte FieldC { get; set; }
}
But as many have found, this becomes a serious maintenance problem if your type has 100 properties and you need to add one between the first 2.
UPDATE
这里列举的例子只是为了示范目的。 在我的具体设想中,我用一个类别界定了信息格式,然后通过该类的特性加以篡改,并 gr清其属性,以了解如何对电文中的具体领域进行划界。 电文中的田地顺序意义重大,因此,本类房地产的顺序必须相当高。
It works currently by just iterating over the return collection from GetProperties
, but since the documentation states it is not recommended I was looking to understand why and what other option do I have?