如何找出属性是否是具有reflection的自动实现的属性?
所以在我的情况下,我正在使用reflection来发现类的结构。 我需要能够通过PropertyInfo对象找出属性是否是自动实现的属性。 我假设reflectionAPI没有公开这样的function,因为自动属性是C#依赖的,但有没有解决方法来获取这些信息?
您可以检查get
或set
方法是否使用CompilerGenerated
属性进行标记。 然后,您可以将其与查找使用CompilerGenerated
属性标记的私有字段进行组合,该属性包含属性的名称和字符串"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; }
这不是万无一失的,非常脆弱,可能不便于Mono。
这应该做:
public static bool IsAutoProperty(this PropertyInfo prop) { return prop.DeclaringType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance) .Any(f => f.Name.Contains("<" + prop.Name + ">")); }
原因是对于自动属性,后备FieldInfo
的Name
属性如下所示:
k__BackingField
由于字符<
和>
不会出现在普通字段中,因此具有这种命名的字段指向自动属性的后备字段。 正如杰森所说,它仍然脆弱。
或者让它更快一点,
public static bool IsAutoProperty(this PropertyInfo prop) { if (!prop.CanWrite || !prop.CanRead) return false; return prop.DeclaringType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance) .Any(f => f.Name.Contains("<" + prop.Name + ">")); }