简体   繁体   中英

Return all fields in an instance of a derived class

I'm looking for a way to return the value of every field in an object in the preferably in the form of a list, but any collection type will work. After a bit of researching, I found this code

FieldInfo[] fields = this.GetType().GetFields();

foreach(FieldInfo field in fields)
    // Perform actions

Would this be the correct way to handle this? Also, if I put this method in the base class, if a derived class calls it will it return all the fields in the derived class or the base class? (Or more simply put would I need to override this for each derived class?)

It's not a problem to do it individually for each class if that's the only way, but I'm just looking to save a bit of code, since I'm going to have some 50+ derived classes.

You're using GetType() , so that will return the fields of the actual object type, not the type you're declaring the method in. You don't need to override

However, your code will currently only get public fields - and I hope you don't have any:)

You probably want something like:

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

I believe that will include inherited fields (as it's not specifying BindingFlags.DeclaredOnly ) but you should check.

Yes, this is a correct way of handling this.

this.GetType() whill return the actual type of the object, so if it is a derived class it will return the type of the derived class and it will work as expected. So: No you do not have to override it in each child class.

One thing: GetType() returns only the public fields. If you also want other fields then you need to use the overload GetType(BindingFlags) and specify the appropriate flags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM