gpt4 book ai didi

c# - FieldInfo[] Type.GetFields() 的顺序有保证吗?

转载 作者:太空宇宙 更新时间:2023-11-03 22:18:44 26 4
gpt4 key购买 nike

目前我在做这样的事情:

class Foo {
// Declare Fields
[FieldName("F_BAR")] public int? Bar;
[FieldName("F_BAZ")] public int? Baz;
[FieldName("BLARG")] public double? Bee;

// And a custom selector
public static string FooFields() {
// which looks something like:
StringBuilder fields = new StringBuilder();
foreach( FieldInfo f in typeof(Foo).GetFields() )
fields.Append(", " +
f.GetCustomAttributes(
typeof(FieldNameAttribute),
false)[0].FieldName );
return fields.ToString().Substring(2);
}
// .. which will be used like this:
public static string ExampleSelect() {
return "select " + Foo.FooFields() + " from tablename";
}

// And a custom reader, formatted for the custom selector
public static Foo Read(DbDataReader reader) {
int i = -1;
return new Foo {
Bar = reader.IsDBNull(++i)
? (int?)null
: Convert.ToInt32(reader.GetValue(i)),
Baz = reader.IsDBNull(++i)
? (int?)null
: Convert.ToInt32(reader.GetValue(i)),
Bee = reader.IsDBNull(++i)
? (double?)null
: Convert.ToDouble(reader.GetValue(i))
};
}
}

目前,它有效。我今天意识到,这取决于从 GetFields() 返回的字段,这些字段按照我在类中声明的顺序排列。这总是预期的行为吗?仅在 .NET 中?

编辑:如果有 cases当它不起作用时,我是否可以假设只要我不做任何破坏缓存的事情它就会起作用?

最佳答案

GetFields 方法不会以任何特定顺序返回 FieldInfo 值。这是来自 MSDN 的相关文档片段

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.

关于c# - FieldInfo[] Type.GetFields() 的顺序有保证吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3992518/

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