public static async Task ComputeRefactoringAsync(RefactoringContext context, EventFieldDeclarationSyntax eventFieldDeclaration)
        {
            if (eventFieldDeclaration.IsParentKind(SyntaxKind.InterfaceDeclaration))
            {
                return;
            }

            VariableDeclarationSyntax variableDeclaration = eventFieldDeclaration.Declaration;

            if (variableDeclaration == null)
            {
                return;
            }

            SemanticModel semanticModel = null;

            foreach (VariableDeclaratorSyntax variableDeclarator in variableDeclaration.Variables)
            {
                if (!context.Span.IsContainedInSpanOrBetweenSpans(variableDeclarator.Identifier))
                {
                    continue;
                }

                semanticModel = semanticModel ?? await context.GetSemanticModelAsync().ConfigureAwait(false);

                var eventSymbol = semanticModel.GetDeclaredSymbol(variableDeclarator, context.CancellationToken) as IEventSymbol;

                if (eventSymbol?.IsStatic != false)
                {
                    continue;
                }

                INamedTypeSymbol containingType = eventSymbol.ContainingType;

                if (containingType == null)
                {
                    return;
                }

                if (!(eventSymbol.Type is INamedTypeSymbol eventHandlerType))
                {
                    continue;
                }

                ITypeSymbol eventArgsSymbol = GetEventArgsSymbol(eventHandlerType, semanticModel);

                if (eventArgsSymbol == null)
                {
                    continue;
                }

                string methodName = "On" + eventSymbol.Name;

                if (containingType.ContainsMember <IMethodSymbol>(
                        $"On{eventSymbol.Name}",
                        methodSymbol => eventArgsSymbol.Equals(methodSymbol.Parameters.SingleOrDefault(shouldThrow: false)?.Type)))
                {
                    continue;
                }

                methodName = NameGenerator.Default.EnsureUniqueMemberName(methodName, containingType);

                context.RegisterRefactoring(
                    $"Generate '{methodName}' method",
                    cancellationToken =>
                {
                    return(RefactorAsync(
                               context.Document,
                               eventFieldDeclaration,
                               eventSymbol,
                               eventArgsSymbol,
                               context.SupportsCSharp6,
                               cancellationToken));
                });
            }
        }
예제 #2
0
 public static bool CanRefactor(EventFieldDeclarationSyntax eventDeclaration)
 {
     return(eventDeclaration.IsParentKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration) &&
            eventDeclaration.Declaration?.Variables.Count == 1);
 }