Java to C# conversion finding public fields of subclass with reflection

I'm currently porting part of a framework over to C# from java.

I used the following line in Java to get the declared fields in order of declaration of the subclass of my abstract class. I would then use this field list to set the values via reflection.

Field[] fields = this.getClass().asSubclass(this.getClass()).getDeclaredFields();

I have tried using the following method to get the same result in C#. But this will return all of the public fields of the super class as well.

IEnumerable<FieldInfo> fields = this.GetType().GetFields().OrderBy(field => field.MetadataToken);

Is there some way i can achieve the same results in C# as the Java method.

To repeat myself, i ONLY need the declared fields of any subclass i make of the current class.

Jon Skeet
people
quotationmark

You just need to use BindingFlags.DeclaredOnly:

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

For example, assuming you want private fields as well, and both instance and static fields - remove the flags you don't want:

var fields = GetType().GetFields(BindingFlags.DeclaredOnly | 
                                 BindingFlags.Public |
                                 BindingFlags.NonPublic |
                                 BindingFlags.Static |
                                 BindingFlags.Instance)
                      .OrderBy(...);

people

See more on this question at Stackoverflow