[英]Checking a property execution body for a particular method invocation
我正在为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>();
现在, propertyObjects
包含带有MyProperty1
和MyProperty2
Enumeration
。
我遍历此枚举并为每个属性获取set
方法。
foreach (var onePropertyObject in propertyObjects)
{
IMethodSymbol setMethod = onePropertyObject.SetMethod;
// setMethod contains "set" method of a processing property.
// how can I test here,
// that setMethod contains invocation of SetPropertyValue() method?
}
据我从文档中了解到,无法从setMethod
变量获取方法主体。
但是,如果我们使用语法树并处理语法树节点,则是可能的。
使用CSharpSyntaxTree解析代码,如下所示:
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>();
然后使用DescendantNodes()
调用获取后代语法节点,并使用GetText()
获取要分析的节点文本。
而已。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.