因此,就我而言,我正在使用反射来发现类的结构。我需要能够通过PropertyInfo对象找出某个属性是否是自动实现的属性。我认为反射API不会公开此类功能,因为自动属性是C#依赖的,但是是否有任何解决方法来获取此信息?

最佳答案

您可以检查getset方法是否用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。

07-24 13:05
查看更多