27

因此,就我而言,我正在使用反射来发现类的结构。我需要能够确定某个属性是否是 PropertyInfo 对象自动实现的属性。我假设反射 API 没有公开这样的功能,因为自动属性依赖于 C#,但是有任何解决方法来获取这些信息吗?

4

2 回答 2

25

您可以检查getorset方法是否标记有该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 上。

于 2010-02-05T20:51:34.077 回答
15

这应该这样做:

public static bool IsAutoProperty(this PropertyInfo prop)
{
    return prop.DeclaringType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
                             .Any(f => f.Name.Contains("<" + prop.Name + ">"));
}

原因是对于自动Name属性,支持的属性FieldInfo看起来像:

<PropertName>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 + ">"));
}
于 2013-05-12T11:07:20.583 回答