Skip to main content
 首页 » 编程设计

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

2024年02月24日18JeffreyZhao

目前我在做这样的事情:

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.