开发者

How can I tell whether a field is the backing-field of an automatic-implemented property?

I'm using reflection to access and store properties and fields. However, to avoid having redundant data, I want to get rid of auto-implemented properties' backing fields, which are also enumerated as normal fields. Looks like these backing fields are named as "{PropertyName}k_BackingField", and it would seem that I could make do with just parsing this string, but I wonder if there's a better approach 开发者_如何学运维than relying on an internal, compiler-provided mangled name.

Thanks.


At least for my classes the compiler annotates those automatic property backing fields with the CompilerGenerated attribute. So you could just check for that, I think.


Well, you can check whether it's a valid C# identifier. If it isn't, that's a pretty good indicator that it's an automatic property. Indeed, if you know that it will have been compiled by a particular version of a particular compiler, you could rely on the naming pattern. Sounds a bit fragile though.

More robustly, if you just want to know whether it's compiler-generated, check whether the FieldInfo has the CompilerGeneratedAttribute applied to it. Now there are other times when the compiler will generated extra fields for you - such as for caching delegates created with lambda expressions which don't need any extra context - but it at least shows that it's not a field explicitly declared by the developer (unless they've also explicitly applied the attribute, of course).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜