反思:从的PropertyInfo获取字段信息 [英] 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?
干杯,埃德
推荐答案
的<$ C房产$ C>获得_ 和集_
方法也得到了 CompilerGeneratedAttributed
适用于他们。虽然没有通过属性不强耦合,有用于自动属性支持字段的命名约定:
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;}
生成一个私人字符串<富> k__BackingField
成员(即<
和>
这里是名称的一部分,因为他们是合法的在IL中但不是在C#。他们没有什么泛型做)
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)
});
这篇关于反思:从的PropertyInfo获取字段信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!