感谢@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<> 代替。
编辑:还要注意,这不会在继承链中进一步搜索类型。就我而言,我知道在调用该方法时我处于最派生的类型。