C#获取原始顺序FieldInfos / PropertyInfos? [英] C# Get FieldInfos/PropertyInfos in the original order?

查看:451
本文介绍了C#获取原始顺序FieldInfos / PropertyInfos?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能得到一个类型FieldInfos / PropertyInfos作为它们在类中规定的顺序的MemberInfo阵列?



 类测试
{
公共BOOL首先{搞定;组; }
公众诠释秒;
公共字符串三{搞定;组; }
}


解决方案

http://msdn.microsoft.com/en-us/library/ch9714z3.aspx




GetFields方法不返回一个特定的顺序领域,如按字母顺序或声明顺序。 。您的代码一定不能依赖于它们返回的字段的顺序,因为该顺序变化




http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx




getProperties方法不返回一个特定的顺序属性,如字母顺序或声明顺序。您的代码一定不能依赖于哪些属性返回的顺序上,因为那为了变化而变化。




您需要自己定义秩序,也许属性:

 类测试
{
[命令(1)]公共BOOL第一{得到;组; }
[订购(2)公众诠释秒;
[命令(3)]公共字符串三{搞定;组; }
}
...
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field,
继承= TRUE,的AllowMultiple = FALSE)]
[ImmutableObject(真) ]
公共密封类OrderAttribute:属性{
私人只读INT秩序;
公众诠释令{{返回秩序; }}
公共OrderAttribute(INT顺序){this.order =秩序;}
}


How can I get a Types FieldInfos/PropertyInfos as a MemberInfo array in the order they are laid out in the class?

class Test
{
    public bool First { get; set; }
    public int Second;
    public string Third { get; set; }
}

解决方案

http://msdn.microsoft.com/en-us/library/ch9714z3.aspx

The GetFields method does not return fields in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which fields are returned, because that order varies.

http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx

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.

You would need to define order yourself, perhaps with attributes:

class Test
{
    [Order(1)] public bool First { get; set; }
    [Order(2)] public int Second;
    [Order(3)] public string Third { get; set; }
}
...
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, 
    Inherited = true, AllowMultiple = false)]
[ImmutableObject(true)]
public sealed class OrderAttribute : Attribute {
    private readonly int order;
    public int Order { get { return order; } }
    public OrderAttribute(int order) {this.order = order;}
}

这篇关于C#获取原始顺序FieldInfos / PropertyInfos?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆