private static string GetAccessorType(AccessorDeclarationSyntax accessorDeclaration) { string accessorType; if (accessorDeclaration.IsKind(SyntaxKind.AddAccessorDeclaration) || accessorDeclaration.IsKind(SyntaxKind.RemoveAccessorDeclaration)) { accessorType = "event"; } else { var accessorList = accessorDeclaration.Parent; if (accessorList == null) { return null; } var indexerOrProperty = accessorList.Parent; if (indexerOrProperty is IndexerDeclarationSyntax) { accessorType = "indexer set"; } else if (indexerOrProperty is PropertyDeclarationSyntax) { accessorType = "property set"; } else { return null; } } return accessorType; }
public override SyntaxNode VisitAccessorDeclaration(AccessorDeclarationSyntax node) { var propName = node.FirstAncestorOrSelf<PropertyDeclarationSyntax>().Identifier.Text; var fieldName = "_" + propName; BlockSyntax body; if (node.IsKind(SyntaxKind.GetAccessorDeclaration)) { body = SyntaxFactory.Block(SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(fieldName)).NormalizeWhitespace()); } else { var setField = SyntaxFactory.ExpressionStatement( SyntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(fieldName), SyntaxFactory.IdentifierName(@"value"))); var raiseEvent = SyntaxFactory.ExpressionStatement( SyntaxFactory.InvocationExpression( SyntaxFactory.IdentifierName("OnPropertyChanged"), SyntaxFactory.ArgumentList( SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Argument( SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(propName))))))); body = SyntaxFactory.Block(SyntaxFactory.SeparatedList<StatementSyntax>(new StatementSyntax[] { setField, raiseEvent })); } var newDecl = SyntaxFactory.AccessorDeclaration(node.Kind(), body); return newDecl; }