我需要找到符合某些规则的方法,例如
- 必须有返回类型 void
- 必须命名为“Set”
- 必须只接受一个参数
- 参数类型需要与提供的类型相匹配
我开始沿着以下路线走,但似乎代码太多了。我想知道是否有更好的方法?
//find type name of the property
foreach (var propertySymbol in propertiesSymbols)
{
var propertyTypeSyntax =
((PropertyDeclarationSyntax) propertySymbol.DeclaringSyntaxNodes.First()).Type;
var propertyTypeInfo = semanticModel.GetTypeInfo(propertyTypeSyntax);
//find method with a name Set that accepts this type of the property
var allSetMethodsSymbols = classSymbol.GetMembers()
.Where(m => m.Kind == CommonSymbolKind.Method && m.Name.Equals("Set"))
.ToList();
foreach (var setMethodSymbol in allSetMethodsSymbols)
{
var methodDeclarationSyntax =
((MethodDeclarationSyntax) setMethodSymbol.DeclaringSyntaxNodes.First());
var expressionSyntax =
methodDeclarationSyntax.DescendantNodes().OfType<ExpressionSyntax>().First();
var typeInfo = semanticModel.GetTypeInfo(expressionSyntax);
var typeName = typeInfo.Type.Name;
if (typeName == "Void")
{
//now we know it is a method named "Set" and has return type "Void"
//let's see if parameter matches
var parameterSymbols =
methodDeclarationSyntax.DescendantNodes().OfType<ParameterSyntax>()
.ToList();
if (parameterSymbols.Count() == 1)
{
//this one has one parameter
//now let's see if it is of the type needed
var exprSyntax = ((ParameterSyntax) parameterSymbols.First())
.DescendantNodes().OfType<ExpressionSyntax>().First();
var parameterTypeInfo = semanticModel.GetTypeInfo(exprSyntax);
if (parameterTypeInfo.Type.Equals(propertyTypeInfo.Type))
{
//execute method rewriter
}
}
}
}
}
Jason 建议的解决方案:
var propertyTypeInfo = propertySymbol.Type;
//find method with a name Set that accepts this type of the property
IEnumerable<MethodSymbol> allSetMethodsSymbols = classSymbol
.GetMembers()
.Where(m =>m.Kind == CommonSymbolKind.Method && m.Name.Equals("Set"))
.Cast<MethodSymbol>();
var setMethod = allSetMethodsSymbols
.Single(x => x.ReturnsVoid
&& x.Parameters.Count == 1
&& x.Parameters.First().Type == propertyTypeInfo);