简体   繁体   中英

Reflection: Get FieldInfo from PropertyInfo

I'm doing some dynamic code generation using Reflection, and I've come across a situation where I need to get the backing field of a property (if it has one) in order to use its FieldInfo object.

Now, I know you can use

.IsDefined(typeof(CompilerGeneratedAttribute), false);

on a FieldInfo to discover whether it's autogenerated, so I assume there's a similar thing for Properties which auto-generate fields?

Cheers, Ed

The get_ and set_ methods for properties also get the CompilerGeneratedAttributed applied to them. While there is no strong coupling through attributes, there is a naming convention used for the backing fields of an auto property:

public string Foo { get; set;}

Produces a private string <Foo>k__BackingField member (the < and > here are part of the name, as they're legal in IL but not in C#; they have nothing to do with generics).

As an example, this will get a list of all of the auto properties in a class, along with their backing fields:

t.GetProperties().Where(p => 
    (p.GetGetMethod() ?? p.GetSetMethod()).IsDefined(typeof(CompilerGeneratedAttribute), false))
   .Select(p => new 
   { 
      Property = p, 
      Field = t.GetField(string.Format("<{0}>k__BackingField", p.Name),
          System.Reflection.BindingFlags.NonPublic | 
          System.Reflection.BindingFlags.Instance) 
   });

There is no built-in method for doing this since the presence of a property does not necessarily guarantee the presence of a backing field.

I found this article which explains one way of doing it. It involves getting the IL of the property's setter and parsing it looking for evidence of a field being set.

Andrew is right.

Actually, a property is just a "pointer" to methods, usually getters/setters when they are generated by Visual Studio or other high level language (most of the time).

Parsing the setter is not easy, though. And, since internally setters are just another vanilla methods, they can use more than one fields, or none at all, or even call another methods. Perhaps you can come up with a solution for the common scenarios, but you have to parse the IL bytecode.

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