FieldInfo [] Type.GetFields()的顺序是否有保证?

时间:2010-10-21 22:27:05

标签: c# reflection

目前我这样做:

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不起作用,我可以假设只要我不做任何事情来扰乱缓存,它会起作用吗?

1 个答案:

答案 0 :(得分:4)

没有GetFields方法不会以任何特定顺序返回FieldInfo值。以下是MSDN

的相关文档摘要
  

GetFields方法不会按特定顺序返回字段,例如按字母顺序或声明顺序。您的代码不得依赖于返回字段的顺序,因为该顺序会有所不同。

相关问题