简体   繁体   中英

Reflection returns backing fields of read-only properties?

It looks like Reflection returns the backing fields for properties if called like so:

type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)

Is there a way to return all fields which have been declared by the user in the class without any backing fields / compiler-generated fields / etc.?

EDIT: Is it safe to rely on the [CompilerGenerated] attribute?

All such fields are marked with CompilerGeneratedAttribute, so you can filter like this:

var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
            .Where(f => f.GetCustomAttribute<CompilerGeneratedAttribute>() == null).ToArray();

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