C# 检查特定方法调用的属性执行体

C# 检查特定方法调用的属性执行体,c#,roslyn-code-analysis,C#,Roslyn Code Analysis,我正在为C#编译器开发一个分析器。我的任务之一是确保每个类属性的set方法调用其执行体中的特定方法 假设我有以下简单的类: public class SomeClass { public void SetPropertyValue(int propertyValue) { // some code here } } public class MyClass : SomeClass { public int MyProperty1 {

我正在为C#编译器开发一个分析器。我的任务之一是确保每个类属性的
set
方法调用其执行体中的特定方法

假设我有以下简单的类:

public class SomeClass
{
    public void SetPropertyValue(int propertyValue)
    {
        // some code here
    }
}

public class MyClass : SomeClass
{
    public int MyProperty1
    {
        set => SetPropertyValue(value);
    }

    public int MyProperty2
    {
        set => AnotherMethod(value);
    }
}
假设类声明对象存储在
myClassTypeSymbol
中,类型为
INamedTypeSymbol

我通过调用获取所有属性对象进行分析:

var propertyObjects = myClassTypeSymbol.OfType<IPropertySymbol>();

据我从文档中了解,无法从
setMethod
变量获取方法体

但如果我们使用语法树和处理语法树节点,这是可能的

用于解析代码,如下所示:

var tree = CSharpSyntaxTree.ParseText(@"
   // code to be analyzed goes here
");
然后获取语法树的根节点:

SyntaxNode rootNode = tree.GetRoot();
然后您可以获得声明的类、方法和属性:

var classes = rootNode.DescendantNodes().OfType<ClassDeclarationSyntax>();
var methods = rootNode.DescendantNodes().OfType<MethodDeclarationSyntax>();
var properties = rootNode.DescendantNodes().OfType<PropertyDeclarationSyntax>();
var classes=rootNode.degenantnodes().OfType();
var methods=rootNode.degenantnodes().OfType();
var properties=rootNode.degenantnodes().OfType();
然后使用
genderantnodes()
调用获取子代语法节点,并使用
GetText()
获取要分析的节点文本


就这样。

据我从文档中了解,无法从
setMethod
变量获取方法体

但如果我们使用语法树和处理语法树节点,这是可能的

用于解析代码,如下所示:

var tree = CSharpSyntaxTree.ParseText(@"
   // code to be analyzed goes here
");
然后获取语法树的根节点:

SyntaxNode rootNode = tree.GetRoot();
然后您可以获得声明的类、方法和属性:

var classes = rootNode.DescendantNodes().OfType<ClassDeclarationSyntax>();
var methods = rootNode.DescendantNodes().OfType<MethodDeclarationSyntax>();
var properties = rootNode.DescendantNodes().OfType<PropertyDeclarationSyntax>();
var classes=rootNode.degenantnodes().OfType();
var methods=rootNode.degenantnodes().OfType();
var properties=rootNode.degenantnodes().OfType();
然后使用
genderantnodes()
调用获取子代语法节点,并使用
GetText()
获取要分析的节点文本


就是这样。

这是用于单元测试的吗?是的,是用于单元测试的。您可以更改
某个类吗?如果是这样,一个明显的建议是从
SetPropertyValue()
引发
PropertyChanged
样式事件-但我想您已经想到并放弃了这个想法…不,我不允许更改父类。我认为应该有一种方法来检查特定方法调用的
setMethod
内容。我错了吗?这是单元测试吗?是的,这是单元测试。你可以更改
SomeClass
?如果是这样,一个明显的建议是从
SetPropertyValue()
引发
PropertyChanged
样式事件-但我想您已经想到并放弃了这个想法…不,我不允许更改父类。我认为应该有一种方法来检查特定方法调用的
setMethod
内容。我错了吗?