感謝轉到@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();
}
}
請注意,我手動比較了嵌套循環中的字段。如果你有深層次的嵌套類或怪異的大類,可以隨意使用HashSet代替。
編輯:也請注意,這不會在繼承鏈中進一步搜索類型。在我的情況下,我知道我在調用方法時處於派生類型最多的狀態。
FlattenHierarchy有以下評論指定公共和保護的靜態成員了層次結構應 返回。不會返回繼承類中的私有靜態成員。靜態 成員包括字段,方法,事件和屬性。嵌套類型不返回。它提到static這個詞,這讓我認爲它不適用於任何靜態成員 – R2D2 2018-01-18 11:36:27