Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Reflection why GetFields list fields that I haven't created ? How to exclude them?

Tags:

c#

.net

wpf

This code returns fields that I created but also some system fields (I'm in WPF app) I didn't create myself:

FieldInfo[] fieldInfos;
fieldInfos = this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

How to exclude the system fields and keep only my own ?

Update: these fields are not fields I inherited from my own class either.

like image 446
user310291 Avatar asked Jan 29 '11 13:01

user310291


1 Answers

I assume you have inherited from something other than object - in which case add DeclaredOnly to your GetFields call:

DeclaredOnly

Specifies that only members declared at the level of the supplied type's hierarchy should be considered. Inherited members are not considered.

So you would have:

FieldInfo[] fieldInfos = this.GetType().GetFields(
     BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
like image 98
Marc Gravell Avatar answered Sep 28 '22 20:09

Marc Gravell