本文整理汇总了C#中Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext.RegisterRefactoring方法的典型用法代码示例。如果您正苦于以下问题:C# CodeRefactoringContext.RegisterRefactoring方法的具体用法?C# CodeRefactoringContext.RegisterRefactoring怎么用?C# CodeRefactoringContext.RegisterRefactoring使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext
的用法示例。
在下文中一共展示了CodeRefactoringContext.RegisterRefactoring方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ComputeRefactoringsAsync
public sealed override async Task ComputeRefactoringsAsync(
CodeRefactoringContext context)
{
var document = context.Document;
var documentFileNameWithoutExtension =
Path.GetFileNameWithoutExtension(document.FilePath);
var root = await document.GetSyntaxRootAsync(context.CancellationToken)
.ConfigureAwait(false);
var model = await document.GetSemanticModelAsync(context.CancellationToken)
.ConfigureAwait(false);
var typesToRemove = root.GetTypesToRemove(
model, documentFileNameWithoutExtension);
if (typesToRemove.Length > 1)
{
context.RegisterRefactoring(CodeAction.Create(
"Move types to files in folders",
async token => await ExtractTypesToFilesCodeRefactoringProvider.CreateFiles(
document, root, model, typesToRemove,
_ => _.Replace(".", "\\"), token)));
context.RegisterRefactoring(CodeAction.Create(
"Move types to files in current folder",
async token => await ExtractTypesToFilesCodeRefactoringProvider.CreateFiles(
document, root, model, typesToRemove,
_ => string.Empty, token)));
}
}
示例2: ComputeRefactoringsAsync
public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var node = root.FindNode(context.Span);
if (node.IsKind(SyntaxKind.Argument))
{
var argSyntax = (ArgumentSyntax)node;
if (argSyntax == null) return;
//Exit if not valid XML
if (!IsXml(argSyntax.Expression.GetFirstToken().ValueText)) return;
var action = CodeAction.Create("Format XML", c => FormatXmlAsync(context.Document, argSyntax, c));
context.RegisterRefactoring(action);
}
if (node.IsKind(SyntaxKind.StringLiteralExpression))
{
var sleSyntax = (LiteralExpressionSyntax)node;
if (sleSyntax == null) return;
//Exit if not valid XML
var text = sleSyntax.GetFirstToken().ValueText;
if (!IsXml(text)) return;
var action = CodeAction.Create("Format XML", c => FormatXmlAsync(context.Document, sleSyntax, c));
context.RegisterRefactoring(action);
}
}
示例3: ComputeRefactoringsAsync
//*** This is the entry point when user hits Ctrl + . ***
public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
// Find the Property at the selection
var node = root.FindNode(context.Span);
var property = node.FirstAncestorOrSelf<PropertyDeclarationSyntax>();
if (property == null)
{
return; // No property here... move along!
}
// Check if user is on an Auto property
if (property.IsAutoProperty() || property.IsExpressionProperty())
{
// Auto Property is selected (Get ready for EXPLOSION)
var explodeAction = CodeAction.Create("Explode Property...", c => ExplodePropertyAsync(root, context.Document, property, c));
context.RegisterRefactoring(explodeAction); // Register Explode Code Action (This will show Explode Property... in the context menu)
}
else if (property.HasGetter())
{
// Full Property is selected (Get ready to CRUNCH)
var implodeAction = CodeAction.Create("Crunch Property...", c => CrunchPropertyAsync(root, context.Document, property, c));
context.RegisterRefactoring(implodeAction); // Register Crunch Code Action (This will show Crunch Property... in the context menu)
}
}
示例4: ComputeRefactoringsAsync
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var document = context.Document;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
return;
var span = context.Span;
if (!span.IsEmpty)
return;
var cancellationToken = context.CancellationToken;
if (cancellationToken.IsCancellationRequested)
return;
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (model.IsFromGeneratedCode(cancellationToken))
return;
var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
SyntaxToken token = root.FindToken(span.Start);
if (!token.IsKind(SyntaxKind.IdentifierToken))
return;
var property = token.Parent as PropertyDeclarationSyntax;
if (property == null || !property.Identifier.Span.Contains(span))
return;
if (IsEmptyComputedProperty(property))
{
context.RegisterRefactoring(
CodeActionFactory.Create(
token.Span,
DiagnosticSeverity.Info,
GettextCatalog.GetString("Convert to auto-property"),
t2 =>
{
var newRoot = root.ReplaceNode(property, CreateNewProperty(property).WithAdditionalAnnotations(Formatter.Annotation).WithLeadingTrivia(property.GetLeadingTrivia()));
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
)
);
return;
}
var field = GetBackingField(model, property);
if (!IsValidField(field, property.Parent as TypeDeclarationSyntax))
return;
//variable declarator->declaration->field declaration
var backingFieldNode = root.FindNode(field.Locations.First().SourceSpan).Ancestors().OfType<FieldDeclarationSyntax>().First();
var propertyAnnotation = new SyntaxAnnotation();
var fieldAnnotation = new SyntaxAnnotation();
//annotate our property node and our field node
root = root.ReplaceNode((SyntaxNode)property, property.WithAdditionalAnnotations(propertyAnnotation));
root = root.ReplaceNode((SyntaxNode)root.FindNode(backingFieldNode.Span), backingFieldNode.WithAdditionalAnnotations(fieldAnnotation));
context.RegisterRefactoring(
CodeActionFactory.Create(token.Span, DiagnosticSeverity.Info, GettextCatalog.GetString("Convert to auto-property"),
PerformAction(document, model, root, field.Name, CreateNewProperty(property), propertyAnnotation, fieldAnnotation))
);
}
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:58,代码来源:ReplacePropertyWithBackingFieldWithAutoPropertyCodeRefactoringProvider.cs
示例5: ComputeRefactoringsAsync
public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
if (!await TypeAndFileNameMismatch(context))
return;
context.RegisterRefactoring(await new RenameTypeRefactoring(context).GetCodeAction());
context.RegisterRefactoring(await new RenameFileRefactoring(DTE,context).GetCodeAction());
context.RegisterRefactoring(await new MoveTypeToFileRefactoring(context).GetCodeAction());
}
示例6: ComputeRefactoringsAsync
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var document = context.Document;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
return;
var span = context.Span;
if (!span.IsEmpty)
return;
var cancellationToken = context.CancellationToken;
if (cancellationToken.IsCancellationRequested)
return;
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (model.IsFromGeneratedCode(cancellationToken))
return;
var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var node = root.FindNode(span) as BinaryExpressionSyntax;
if (node == null || !(node.IsKind(SyntaxKind.EqualsExpression) || node.IsKind(SyntaxKind.NotEqualsExpression)))
return;
context.RegisterRefactoring(
CodeActionFactory.Create(
span,
DiagnosticSeverity.Info,
GettextCatalog.GetString("To 'Equals' call"),
t2 => Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode((SyntaxNode)node, CreateEquals(model, node))))
)
);
}
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:27,代码来源:ConvertEqualityOperatorToEqualsCodeRefactoringProvider.cs
示例7: ComputeRefactoringsAsync
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var document = context.Document;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
return;
var span = context.Span;
if (!span.IsEmpty)
return;
var cancellationToken = context.CancellationToken;
if (cancellationToken.IsCancellationRequested)
return;
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (model.IsFromGeneratedCode(cancellationToken))
return;
var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(span.Start);
if (!token.IsKind(SyntaxKind.StringLiteralToken) || token.Value.ToString() != "")
return;
context.RegisterRefactoring(
CodeActionFactory.Create(
token.Span,
DiagnosticSeverity.Info,
GettextCatalog.GetString("Use 'string.Empty'"),
t2 =>
{
var newRoot = root.ReplaceNode((SyntaxNode)token.Parent, SyntaxFactory.ParseExpression("string.Empty"));
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
)
);
}
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:32,代码来源:UseSystemStringEmptyCodeRefactoringProvider.cs
示例8: ComputeRefactoringsAsync
public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
try
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
// Find the node at the selection.
var node = root.FindNode(context.Span);
// Only offer a refactoring if the selected node is a method declaration node.
var methodDecl = node as MethodDeclarationSyntax;
if (methodDecl == null) return;
// Only offer a refactoring if the method declaration node matches a signature pattern we recognize.
var refactoringProviderList = BuildRefactoringProviderList();
foreach (var mapper in refactoringProviderList)
{
if (await mapper.CanRefactor(context.Document, methodDecl))
{
// Register mapping code action.
var action = CodeAction.Create(mapper.Description, c => mapper.Refactor(context.Document, methodDecl, c));
context.RegisterRefactoring(action);
break;
}
}
}
catch (Exception ex)
{
string error = ex.ToString();
}
}
示例9: ComputeRefactoringsAsync
public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var document = context.Document;
var textSpan = context.Span;
var cancellationToken = context.CancellationToken;
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false) as CompilationUnitSyntax;
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
// if length is 0 then no particular range is selected, so pick the first enclosing member
if (textSpan.Length == 0)
{
var decl = root.FindToken(textSpan.Start).Parent.AncestorsAndSelf().OfType<MemberDeclarationSyntax>().FirstOrDefault();
if (decl != null)
{
textSpan = decl.FullSpan;
}
}
var properties = ExpansionChecker.GetExpandableProperties(textSpan, root, model);
if (properties.Any())
{
#pragma warning disable RS0005
context.RegisterRefactoring(
CodeAction.Create("Apply INotifyPropertyChanged pattern", (c) =>
ImplementNotifyPropertyChangedAsync(document, root, model, properties, c)));
#pragma warning restore RS0005
}
}
示例10: ComputeRefactoringsAsync
public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var node = root.FindNode(context.Span);
if (node == null) return;
//process string literal or interpolated string.
if (!node.IsKind(SyntaxKind.StringLiteralExpression))
{
node = node.AncestorsAndSelf().OfType<InterpolatedStringExpressionSyntax>().FirstOrDefault();
}
if (node == null) return;
if (node.IsKind(SyntaxKind.StringLiteralExpression) || node.IsKind(SyntaxKind.InterpolatedStringExpression))
{
var tree = root.SyntaxTree;
var lines = tree.GetText().Lines;
// find add-expression in the same line (left end and right start).
var addExpression = node.Ancestors()
.TakeWhile(n => n.IsKind(SyntaxKind.AddExpression))
.Cast<BinaryExpressionSyntax>()
.TakeWhile(n => lines.GetLinePosition(n.Left.Span.End).Line == lines.GetLinePosition(n.Right.Span.Start).Line)
.LastOrDefault();
if (addExpression != null)
{
var action = CodeAction.Create("Integrate strings", c => IntegrateStringsAsync(context.Document, addExpression, c), ActionKeyStringIntegration);
context.RegisterRefactoring(action);
}
}
}
开发者ID:miya2000,项目名称:StringIntegrationCodeRefactoring,代码行数:35,代码来源:StringIntegrationCodeRefactoringProvider.cs
示例11: ComputeRefactoringsAsync
public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var node = root.FindNode(context.Span);
var currentRoot = await context.Document.GetSyntaxTreeAsync().Result.GetRootAsync();
var classCount = currentRoot.DescendantNodesAndSelf().Where(n => n is ClassStatementSyntax).Count();
// only for a type declaration node that doesn't match the current file name
// also omit all private classes
var typeDecl = node as ClassStatementSyntax;
var className = typeDecl.Identifier.GetIdentifierText() + ".vb";
//Is the name of the file the same as the name of the class then do nothing.
if(typeDecl == null || context.Document.Name.ToLowerInvariant() == className.ToLowerInvariant() || typeDecl.Modifiers.Any(SyntaxKind.PrivateKeyword))
{ return; }
//We know the name of the class is not the same as the file. If this is the only class in the file we will offer a rename file refactoring.
if(classCount == 1)
{
var renameFileActino = CodeAction.Create("Rename file to \"" + className + "\" ", c => RenameDocumentAsync(context.Document, className,c));
}else
{
var action = CodeAction.Create("Move class to file \"" + className + "\" ", c => MoveClassIntoNewFileAsync(context.Document, typeDecl, className, c));
context.RegisterRefactoring(action);
}
}
示例12: ComputeRefactoringsAsync
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var document = context.Document;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
return;
var span = context.Span;
if (!span.IsEmpty)
return;
var cancellationToken = context.CancellationToken;
if (cancellationToken.IsCancellationRequested)
return;
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (model.IsFromGeneratedCode(cancellationToken))
return;
var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var node = root.FindToken(span.Start).Parent;
if (node.Parent == null || node.Parent.Parent == null || !node.Parent.Parent.IsKind(SyntaxKind.InvocationExpression))
return;
var symbol = model.GetSymbolInfo(node.Parent).Symbol;
if (symbol == null || symbol.Kind != SymbolKind.Method || symbol.ContainingType.SpecialType != SpecialType.System_Enum || symbol.Name != "HasFlag")
return;
var invocationNode = (InvocationExpressionSyntax)node.Parent.Parent;
var arg = invocationNode.ArgumentList.Arguments.Select(a => a.Expression).First();
if (!arg.DescendantNodesAndSelf().OfType<BinaryExpressionSyntax>().All(bop => bop.IsKind(SyntaxKind.BitwiseOrExpression)))
return;
context.RegisterRefactoring(
CodeActionFactory.Create(node.Span, DiagnosticSeverity.Info, GettextCatalog.GetString("To bitwise flag comparison"), t2 => Task.FromResult(PerformAction(document, root, invocationNode)))
);
}
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:31,代码来源:ConvertHasFlagsToBitwiseFlagComparisonCodeRefactoringProvider.cs
示例13: ComputeRefactoringsAsync
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var document = context.Document;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
return;
var span = context.Span;
if (!span.IsEmpty)
return;
var cancellationToken = context.CancellationToken;
if (cancellationToken.IsCancellationRequested)
return;
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (model.IsFromGeneratedCode(cancellationToken))
return;
var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
ExpressionSyntax expr;
SyntaxToken token;
if (!GetRelationalExpression(root, span, out expr, out token))
return;
context.RegisterRefactoring(
CodeActionFactory.Create(
span,
DiagnosticSeverity.Info,
string.Format(GettextCatalog.GetString("Negate '{0}'"), expr),
t2 =>
{
var newRoot = root.ReplaceNode((SyntaxNode)
expr,
CSharpUtil.InvertCondition(expr).WithAdditionalAnnotations(Formatter.Annotation)
);
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
)
);
}
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:35,代码来源:NegateLogicalExpressionCodeRefactoringProvider.cs
示例14: ComputeRefactoringsAsync
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var document = context.Document;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
return;
var span = context.Span;
if (!span.IsEmpty)
return;
var cancellationToken = context.CancellationToken;
if (cancellationToken.IsCancellationRequested)
return;
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (model.IsFromGeneratedCode(cancellationToken))
return;
var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(span.Start);
var parameter = token.Parent as ParameterSyntax;
if (parameter != null)
{
var ctor = parameter.Parent.Parent as ConstructorDeclarationSyntax;
if (ctor == null)
return;
context.RegisterRefactoring(
CodeActionFactory.Create(
parameter.Span,
DiagnosticSeverity.Info,
GettextCatalog.GetString("Initialize field from parameter"),
t2 =>
{
var newFieldName = NameProposalService.GetNameProposal(parameter.Identifier.ValueText, SyntaxKind.FieldDeclaration, Accessibility.Private, false, context.Document, ctor.SpanStart);
var newField = SyntaxFactory.FieldDeclaration(
SyntaxFactory.VariableDeclaration(
parameter.Type,
SyntaxFactory.SingletonSeparatedList<VariableDeclaratorSyntax>(SyntaxFactory.VariableDeclarator(newFieldName)))
).WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)))
.WithAdditionalAnnotations(Formatter.Annotation);
var assignmentStatement = SyntaxFactory.ExpressionStatement(
SyntaxFactory.AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ThisExpression(), SyntaxFactory.IdentifierName(newFieldName)),
SyntaxFactory.IdentifierName(newFieldName)
)
).WithAdditionalAnnotations(Formatter.Annotation);
var trackedRoot = root.TrackNodes(ctor);
var newRoot = trackedRoot.InsertNodesBefore(trackedRoot.GetCurrentNode(ctor), new List<SyntaxNode>() {
newField
});
newRoot = newRoot.ReplaceNode(newRoot.GetCurrentNode(ctor), ctor.WithBody(
ctor.Body.WithStatements(SyntaxFactory.List<StatementSyntax>(new[] { assignmentStatement }.Concat(ctor.Body.Statements)))
));
return Task.FromResult(document.WithSyntaxRoot(newRoot));
})
);
}
}
开发者ID:ChrisCross67,项目名称:RefactoringEssentials,代码行数:60,代码来源:InitializeFieldFromConstructorParameterCodeRefactoringProvider.cs
示例15: ComputeRefactoringsAsync
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var document = context.Document;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
return;
var span = context.Span;
if (!span.IsEmpty)
return;
var cancellationToken = context.CancellationToken;
if (cancellationToken.IsCancellationRequested)
return;
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (model.IsFromGeneratedCode(cancellationToken))
return;
var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(span.Start);
if (!token.IsKind(SyntaxKind.EqualsToken))
return;
var node = token.Parent as AssignmentExpressionSyntax;
if (node == null)
return;
var assignment = CreateAssignment(node);
if (assignment == null)
return;
assignment = assignment.WithAdditionalAnnotations(Formatter.Annotation);
context.RegisterRefactoring(
CodeActionFactory.Create(span, DiagnosticSeverity.Info, String.Format(GettextCatalog.GetString("To '{0}='"), node.Left.ToString()), document.WithSyntaxRoot(
root.ReplaceNode((SyntaxNode)node, assignment)))
);
}
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:30,代码来源:ReplaceWithOperatorAssignmentCodeRefactoringProvider.cs