Short version: Can I rely on auto property backing fields having names in a certain format? Like "<my_member>k__BackingField
"?
I am writing some serialisation code, which uses reflection to figure out which fields/properties to serialise.
Currently it serialises auto properties using Type.GetMembers
, then using PropertyInfo.GetGetMethod
and PropertyInfo.GetSetMethod
on property members, checking that they have the CompilerGeneratedAttribute
(to make sure they are auto), then invoking those methods to get and set the underlying value.
This is usually fine, but it fails for e.g. C# 6 "read-only auto-properties", which lack a setter, but which should conceptually work ok because I do support serialising read-only fields.
So I wonder if I should just find the backing field for auto properties and serialise that instead - but I can't find any API to get a PropertyInfo
's corresponding backing field - instead I just see that there happens to be a PropertyInfo
, and then a FieldInfo
with a name like "<my_member>k__BackingField
" - but I don't know if I can rely on that, or if it's something that may change between compilations/compiler versions.
Aucun commentaire:
Enregistrer un commentaire