目前,我做这样的事情:FieldInfo [] Type.GetFields()的顺序是否有保证?
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()上的LINQ排序。 – maxwellb 2011-06-09 21:35:18
对于GetProperties()也是如此,因此也适用于RuntimeReflectionExtensions.GetRuntimeProperties()和RuntimeReflectionExtensions.GetRuntimeFields()。 – 2016-09-14 04:55:58