此代码返回我创建的字段以及一些系统字段(我在 WPF 应用程序中)我没有创建自己:
FieldInfo[] fieldInfos;
fieldInfos = this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
如何排除系统字段,只保留我自己的?
更新:这些字段也不是我从我自己的类继承的字段。
最佳答案
我假设您继承自 object
以外的东西 - 在这种情况下添加 DeclaredOnly
到您的 GetFields
调用:
DeclaredOnly
Specifies that only members declared at the level of the supplied type's hierarchy should be considered. Inherited members are not considered.
所以你会:
FieldInfo[] fieldInfos = this.GetType().GetFields(
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
关于C# 反射(reflection)为什么 GetFields 会列出我尚未创建的字段?如何排除它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4837010/