确定 属性 是否为自动 属性

Determine if a property is an auto property

我想弄清楚 属性 是否是自动 属性 即 public int Foo { get; set; }

盯着 PropertyDeclarationSyntaxIPropertySymbol 看了一会儿,但没有找到任何东西。

猜想另一种方法是评估get & set是否不包含任何语句的扩展方法是一种方法,但感觉不是很优雅。

检查 PropertyDeclarationSyntaxAccessorList 中的任何 AccessorDeclarationSyntax 是否具有非空 Body

您可以通过使用语法可视化工具(来自 Roslyn SDK 扩展)查看任何 属性 声明来了解这一点。

这个blog给出了很好的解释:

综上所述,

var isExplicitProperty = node
    .DescendantNodesAndSelf()
    .OfType<PropertyDeclarationSyntax>()
    .Any(prop =>
    {
        if(prop.AccessorList != null)
        {
            return prop.AccessorList.Accessors
                .Any(a => a.Body != null || a.ExpressionBody != null);
        }

        // readonly arrow property declaration
        return true;
    });

基于内部 source code