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

标签 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当它不起作用时,我是否可以假设只要我不做任何破坏缓存的事情它就会起作用?

最佳答案

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/

相关文章:

c# - WPF旋转按钮

c# - 如何确定 Windows CE 设备上的可用空间?

c# - 如何向 Grid.Mvc 添加导出功能,以便将当前搜索结果导出到 excel?

java - 我可以使用 CDI 查找任何 bean 中所有带限定符注释的方法吗?

c# - 使用正则表达式获取文件名的中间部分

java - 如何获取间接实现的泛型接口(interface)的实际类型参数?

c# - 如何使用类型参数从泛型类型中提取原始泛型类型

java - 在 Java Bean 中获取 "last visited field"

reflection - 如何对 fsx 文件中的模块进行 typeof?

c# - 绑定(bind)复选框命令