gpt4 book ai didi

C#按原始顺序获取FieldInfos/PropertyInfos?

转载 作者:IT王子 更新时间:2023-10-29 04:24:32 29 4
gpt4 key购买 nike

如何按照类中的排列顺序获取类型 FieldInfos/PropertyInfos 作为 MemberInfo 数组?

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.

您需要自己定义顺序,可能需要使用属性:

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?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5473455/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com