10

在 C# 中,如果Type.GetFields()与表示派生类的类型一起使用,它将返回 a) 派生类中所有显式声明的字段,b) 派生类中自动属性的所有支持字段,以及 c) 基类中所有显式声明的字段班级。

为什么缺少基类中自动属性的 d) 支持字段?

例子:

public class Base {
    public int Foo { get; set; }
}
public class Derived : Base {
    public int Bar { get; set; }
}
class Program {
    static void Main(string[] args) {
        FieldInfo[] fieldInfos = typeof(Derived).GetFields(
            BindingFlags.Public | BindingFlags.NonPublic |
            BindingFlags.Instance | BindingFlags.FlattenHierarchy
        );
        foreach(FieldInfo fieldInfo in fieldInfos) {
            Console.WriteLine(fieldInfo.Name);
        }
    }
}

这将只显示 Bar 的支持字段,而不是 Foo。

4

3 回答 3

11

作为背景场的场对反射没有影响。支持字段的唯一相关属性是它们是私有的。

反射函数不会返回基类的私有成员,即使您使用FlattenHierarchy. 您将需要手动循环遍历您的类层次结构,并在每个层次上询问私有字段。

我认为FlattenHierarchy编写的目的是显示您查看的类中的代码可见的所有成员。因此,基成员可以被派生类中具有相同名称的成员隐藏/隐藏,而私有成员则根本不可见。

于 2012-02-08T21:38:58.413 回答
7

这是使用 HashSet 的修订版:

public static FieldInfo[] GetFieldInfosIncludingBaseClasses(Type type, BindingFlags bindingFlags)
{
    FieldInfo[] fieldInfos = type.GetFields(bindingFlags);

    // If this class doesn't have a base, don't waste any time
    if (type.BaseType == typeof(object))
    {
        return fieldInfos;
    }
    else
    {   // Otherwise, collect all types up to the furthest base class
        var currentType = type;
        var fieldComparer = new FieldInfoComparer();
        var fieldInfoList = new HashSet<FieldInfo>(fieldInfos, fieldComparer);
        while (currentType != typeof(object))
        {
            fieldInfos = currentType.GetFields(bindingFlags);
            fieldInfoList.UnionWith(fieldInfos);
            currentType = currentType.BaseType;
        }
        return fieldInfoList.ToArray();
    }
}

private class FieldInfoComparer : IEqualityComparer<FieldInfo>
{
    public bool Equals(FieldInfo x, FieldInfo y)
    {
        return x.DeclaringType == y.DeclaringType && x.Name == y.Name;
    }

    public int GetHashCode(FieldInfo obj)
    {
        return obj.Name.GetHashCode() ^ obj.DeclaringType.GetHashCode();
    }
}
于 2012-09-07T11:15:08.853 回答
1

感谢@CodeInChaos 快速而完整的回答!

万一其他人偶然发现了这一点,这里有一个快速的解决方法,可以将字段跟踪到最远的基类。

/// <summary>
///   Returns all the fields of a type, working around the fact that reflection
///   does not return private fields in any other part of the hierarchy than
///   the exact class GetFields() is called on.
/// </summary>
/// <param name="type">Type whose fields will be returned</param>
/// <param name="bindingFlags">Binding flags to use when querying the fields</param>
/// <returns>All of the type's fields, including its base types</returns>
public static FieldInfo[] GetFieldInfosIncludingBaseClasses(
    Type type, BindingFlags bindingFlags
) {
    FieldInfo[] fieldInfos = type.GetFields(bindingFlags);

    // If this class doesn't have a base, don't waste any time
    if(type.BaseType == typeof(object)) {
        return fieldInfos;
    } else { // Otherwise, collect all types up to the furthest base class
        var fieldInfoList = new List<FieldInfo>(fieldInfos);
        while(type.BaseType != typeof(object)) {
            type = type.BaseType;
            fieldInfos = type.GetFields(bindingFlags);

            // Look for fields we do not have listed yet and merge them into the main list
            for(int index = 0; index < fieldInfos.Length; ++index) {
                bool found = false;

                for(int searchIndex = 0; searchIndex < fieldInfoList.Count; ++searchIndex) {
                    bool match =
                        (fieldInfoList[searchIndex].DeclaringType == fieldInfos[index].DeclaringType) &&
                        (fieldInfoList[searchIndex].Name == fieldInfos[index].Name);

                    if(match) {
                        found = true;
                        break;
                    }
                }

                if(!found) {
                    fieldInfoList.Add(fieldInfos[index]);
                }
            }
        }

        return fieldInfoList.ToArray();
    }
}

请注意,我正在手动比较嵌套 for 循环中的字段。如果您有深度嵌套的类或非常大的类,请随意使用 HashSet<> 代替。

编辑:还要注意,这不会在继承链中进一步搜索类型。就我而言,我知道在调用该方法时我处于最派生的类型。

于 2012-02-08T22:12:14.037 回答