如何找出如果一个属性是一个自动实现的属性与反思? [英] How to find out if a property is an auto-implemented property with reflection?
问题描述
所以,在我的情况下,我做发现使用反射类的结构。我需要能够找出是否一个属性是由PropertyInfo对象自动实现的属性。我认为反射API不会公开这样的功能,因为自动属性是C#依赖,但没有任何解决方法,以获取这些信息?
So in my case i am doing discovery of the structure of a class using reflection. I need to be able to find out if a property is an auto-implemented property by the PropertyInfo object. I assume that the reflection API does not expose such functionality because auto-properties are C# dependent, but is there any workaround to get this information?
推荐答案
您可以检查,看看是否 GET
或设置
法标有编译器生成
属性。然后,您可以结合起来,与查找标有包含属性的名称和字符串BackingField的
。编译器生成
属性的私有字段
You could check to see if the get
or set
method is marked with the CompilerGenerated
attribute. You could then combine that with looking for a private field that is marked with the CompilerGenerated
attribute containing the name of the property and the string "BackingField"
.
也许
public static bool MightBeCouldBeMaybeAutoGeneratedInstanceProperty(
this PropertyInfo info
) {
bool mightBe = info.GetGetMethod()
.GetCustomAttributes(
typeof(CompilerGeneratedAttribute),
true
)
.Any();
if (!mightBe) {
return false;
}
bool maybe = info.DeclaringType
.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(f => f.Name.Contains(info.Name))
.Where(f => f.Name.Contains("BackingField"))
.Where(
f => f.GetCustomAttributes(
typeof(CompilerGeneratedAttribute),
true
).Any()
)
.Any();
return maybe;
}
这不是欺骗的证据,很脆,很可能无法移植到,比方说,单声道。
It's not fool proof, quite brittle and probably not portable to, say, Mono.
这篇关于如何找出如果一个属性是一个自动实现的属性与反思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!