本文整理汇总了C#中Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext类的典型用法代码示例。如果您正苦于以下问题:C# CodeRefactoringContext类的具体用法?C# CodeRefactoringContext怎么用?C# CodeRefactoringContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CodeRefactoringContext类属于Microsoft.CodeAnalysis.CodeRefactorings命名空间,在下文中一共展示了CodeRefactoringContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: ComputeRefactoringsAsync
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var document = context.Document;
var textSpan = context.Span;
var cancellationToken = context.CancellationToken;
// NOTE(DustinCa): Not supported in REPL for now.
if (document.SourceCodeKind == SourceCodeKind.Interactive)
{
return;
}
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
var service = document.GetLanguageService<IGenerateDefaultConstructorsService>();
var result = await service.GenerateDefaultConstructorsAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
if (!result.ContainsChanges)
{
return;
}
var actions = result.GetCodeRefactoring(cancellationToken).Actions;
context.RegisterRefactorings(actions);
}
开发者ID:GloryChou,项目名称:roslyn,代码行数:27,代码来源:GenerateDefaultConstructorsCodeRefactoringProvider.cs
示例2: ComputeRefactoringsAsync
public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var document = context.Document;
var textSpan = context.Span;
var cancellationToken = context.CancellationToken;
var root = (SyntaxNode)await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(textSpan.Start);
// Only trigger if the text span is within the 'if' keyword token of an if-else statement.
if (token.Kind() != SyntaxKind.IfKeyword ||
!token.Span.IntersectsWith(textSpan.Start) ||
!token.Span.IntersectsWith(textSpan.End))
{
return;
}
var ifStatement = token.Parent as IfStatementSyntax;
if (ifStatement == null || ifStatement.Else == null)
{
return;
}
var semanticModel = (SemanticModel)await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
ReturnStatementSyntax returnStatement;
if (ReturnConditionalAnalyzer.TryGetNewReturnStatement(ifStatement, semanticModel, out returnStatement))
{
var action = new ConvertToConditionalCodeAction("Convert to conditional expression", (c) => Task.FromResult(ConvertToConditional(document, semanticModel, ifStatement, returnStatement, c)));
context.RegisterRefactoring(action);
}
}
开发者ID:Rickinio,项目名称:roslyn,代码行数:33,代码来源:CodeRefactoringProvider.cs
示例3: 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);
var token = root.FindToken(textSpan.Start);
if (token.Parent == null)
{
return;
}
var propertyDeclaration = token.Parent.FirstAncestorOrSelf<PropertyDeclarationSyntax>();
// Refactor only properties with both a getter and a setter.
if (propertyDeclaration == null ||
!HasBothAccessors(propertyDeclaration) ||
!propertyDeclaration.Identifier.Span.IntersectsWith(textSpan.Start))
{
return;
}
context.RegisterRefactoring(
new ConvertToAutoPropertyCodeAction("Convert to auto property",
(c) => ConvertToAutoPropertyAsync(document, propertyDeclaration, c)));
}
开发者ID:Rickinio,项目名称:roslyn,代码行数:27,代码来源:CodeRefactoringProvider.cs
示例4: ComputeRefactoringsAsync
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var document = context.Document;
var textSpan = context.Span;
var cancellationToken = context.CancellationToken;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
var model = await document.GetSemanticModelAsync (cancellationToken).ConfigureAwait (false);
if (model.IsFromGeneratedCode (cancellationToken))
return;
var root = await document.GetCSharpSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
if (textSpan.Start >= root.FullSpan.Length)
return;
var token = root.FindToken(textSpan.Start);
if (!token.Span.Contains(textSpan))
{
return;
}
var node = token.Parent.AncestorsAndSelf ().FirstOrDefault (n => n.IsKind(SyntaxKind.UsingDirective) || n.IsParentKind(SyntaxKind.ExternAliasDirective));
if (node == null)
{
return;
}
context.RegisterRefactoring(
new DocumentChangeAction(node.Span, DiagnosticSeverity.Info,
GettextCatalog.GetString ("Sort and remove usings"),
(t) => SortAndRemoveImportsCommandHandler.SortAndRemoveAsync(document, t)));
}
开发者ID:sushihangover,项目名称:monodevelop,代码行数:32,代码来源:SortImportsCodeRefactoringProvider.cs
示例5: 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)
}
}
开发者ID:NielsFilter,项目名称:PropertyExplosion,代码行数:28,代码来源:CodeRefactoringProvider.cs
示例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 token = root.FindToken(span.Start);
var castExpression = token.Parent.AncestorsAndSelf().OfType<CastExpressionSyntax>().FirstOrDefault();
if (castExpression == null || castExpression.IsKind(SyntaxKind.TryCastExpression) || castExpression.Expression.Span.Contains(span))
return;
var type = model.GetTypeInfo(castExpression.Type).Type;
if (type == null || type.IsValueType && !type.IsNullableType())
return;
context.RegisterRefactoring(
CodeActionFactory.Create(
token.Span,
DiagnosticSeverity.Info,
GettextCatalog.GetString("Convert cast to 'TryCast'"),
t2 => Task.FromResult(PerformAction(document, root, castExpression))
)
);
}
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:31,代码来源:ReplaceDirectCastWithSafeCastCodeRefactoringProvider.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.IntegerLiteralToken))
return;
var value = token.Value;
if (!((value is int) || (value is long) || (value is short) || (value is sbyte) ||
(value is uint) || (value is ulong) || (value is ushort) || (value is byte)))
{
return;
}
var literalValue = token.ToString();
if (literalValue.StartsWith("&H", System.StringComparison.OrdinalIgnoreCase))
return;
context.RegisterRefactoring(CodeActionFactory.Create(token.Span, DiagnosticSeverity.Info, GettextCatalog.GetString("To hex"), t2 => Task.FromResult(PerformAction(document, root, token))));
}
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:29,代码来源:ConvertDecToHexCodeRefactoringProvider.cs
示例8: 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)));
}
}
开发者ID:JasonBock,项目名称:CompilerAPIBook,代码行数:29,代码来源:ExtractTypesToFilesCodeRefactoringProvider.cs
示例9: 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
示例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);
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);
}
}
开发者ID:petterek,项目名称:RefactoringEssentials,代码行数:28,代码来源:MoveClassToNewFileCodeRefactoringProvider.cs
示例11: ComputeRefactoringsAsync
public 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);
var token = root.FindToken(textSpan.Start);
if (token.Parent == null)
{
return;
}
var node = token.Parent.FirstAncestorOrSelf<ArgumentListSyntax>();
var createExpression = node?.Parent as ObjectCreationExpressionSyntax;
if (createExpression == null)
return;
var semanticModel = (SemanticModel)await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var typeSymbol = ModelExtensions.GetTypeInfo(semanticModel, createExpression);
var constructors = typeSymbol.Type.GetMembers().Where(x => x.Kind == SymbolKind.Method).Cast<IMethodSymbol>().Where(x => x.MethodKind == MethodKind.Constructor);
constructors = constructors.Where(x => HasMoreArguments(x, node.Arguments, semanticModel));
foreach (var constructor in constructors)
{
ReportForUnimplemented(context, constructor, semanticModel, node, typeSymbol);
}
}
开发者ID:jarlrasm,项目名称:PhilTheCartographer,代码行数:30,代码来源:FillConstrutorRefactoring.cs
示例12: GetRefactoringFromProvider
private async Task<CodeRefactoring> GetRefactoringFromProvider(
CodeRefactoringProvider provider,
IExtensionManager extensionManager,
CodeRefactoringContext context)
{
context.CancellationToken.ThrowIfCancellationRequested();
if (extensionManager.IsDisabled(provider))
{
return null;
}
try
{
var actions = await provider.GetRefactoringsAsync(context).ConfigureAwait(false);
if (actions != null && actions.Count() > 0)
{
return new CodeRefactoring(provider, actions);
}
}
catch (OperationCanceledException)
{
// We don't want to catch operation canceled exceptions in the catch block
// below. So catch is here and rethrow it.
throw;
}
catch (Exception e)
{
extensionManager.HandleException(provider, e);
}
return null;
}
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:32,代码来源:CodeRefactoringProducer.cs
示例13: GetCodeRefactoringsAsync
public async Task<IEnumerable<CodeRefactoring>> GetCodeRefactoringsAsync(
Document document,
TextSpan state,
CancellationToken cancellationToken)
{
var optionService = WorkspaceServices.WorkspaceService.GetService<IOptionService>(document.Project.Solution.Workspace);
if (!optionService.GetOption(EditorComponentOnOffOptions.CodeRefactorings))
{
return SpecializedCollections.EmptyEnumerable<CodeRefactoring>();
}
using (Logger.LogBlock(FeatureId.CodeActions, FunctionId.CodeActions_RefactoringProducer_AddNewItemsWorker, cancellationToken))
{
var extensionManager = document.GetExtensionManager();
var tasks = new List<Task<CodeRefactoring>>();
var context = new CodeRefactoringContext(document, state, cancellationToken);
foreach (var provider in this.GetProviders(document))
{
tasks.Add(Task.Run(() => GetRefactoringFromProvider(
provider,
extensionManager,
context)));
}
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
return results.WhereNotNull();
}
}
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:29,代码来源:CodeRefactoringProducer.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 node = root.FindNode(span) as IfStatementSyntax;
ExpressionSyntax condition, target;
AssignmentExpressionSyntax trueAssignment, falseAssignment;
if (!ParseIfStatement(node, out condition, out target, out trueAssignment, out falseAssignment))
return;
ExpressionSyntax trueAssignmentExpr = trueAssignment.Right;
ExpressionSyntax falseAssignmentExpr = falseAssignment.Right;
var assignmentTargetType = model.GetTypeInfo(trueAssignment.Left).Type;
var trueAssignmentExprType = model.GetTypeInfo(trueAssignment.Right).Type;
var falseAssignmentExprType = model.GetTypeInfo(falseAssignment.Right).Type;
if ((trueAssignmentExprType == null) || (falseAssignmentExprType == null))
return;
if (assignmentTargetType.CompareTo(trueAssignmentExprType) != 0)
{
trueAssignmentExpr = SyntaxFactory.CastExpression(
assignmentTargetType.GenerateTypeSyntax(Simplifier.Annotation),
trueAssignmentExpr).WithAdditionalAnnotations(Formatter.Annotation);
}
if (assignmentTargetType.CompareTo(falseAssignmentExprType) != 0)
{
falseAssignmentExpr = SyntaxFactory.CastExpression(
assignmentTargetType.GenerateTypeSyntax(Simplifier.Annotation),
falseAssignmentExpr).WithAdditionalAnnotations(Formatter.Annotation);
}
context.RegisterRefactoring(
CodeActionFactory.Create(span, DiagnosticSeverity.Info, GettextCatalog.GetString("To '?:' expression"),
t2 =>
{
var newRoot = root.ReplaceNode((SyntaxNode)node,
SyntaxFactory.ExpressionStatement(
SyntaxFactory.AssignmentExpression(
trueAssignment.Kind(),
trueAssignment.Left,
SyntaxFactory.ConditionalExpression(condition, trueAssignmentExpr, falseAssignmentExpr)
)
).WithAdditionalAnnotations(Formatter.Annotation).WithLeadingTrivia(node.GetLeadingTrivia())
);
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
)
);
}
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:60,代码来源:ConvertIfStatementToConditionalTernaryExpressionCodeRefactoringProvider.cs
示例15: InsertionResult
public InsertionResult(CodeRefactoringContext context, SyntaxNode node, INamedTypeSymbol type, Location location)
{
this.Context = context;
this.Node = node;
this.Type = type;
this.Location = location;
}
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:7,代码来源:InsertionResult.cs
示例16: 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
}
}
开发者ID:Rickinio,项目名称:roslyn,代码行数:30,代码来源:CodeRefactoringProvider.cs
示例17: 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 parameter = node as ParameterSyntax;
if ((parameter == null)
|| !(node?.Parent?.Parent is ConstructorDeclarationSyntax)) // constructor parameters only
{
return;
}
var parameterName = RoslynHelpers.GetParameterName(parameter);
var underscorePrefix = "_" + parameterName;
var uppercase = parameterName.Substring(0, 1).ToUpper() + parameterName.Substring(1);
if (RoslynHelpers.VariableExists(root, parameterName, underscorePrefix, uppercase))
{
return;
}
var action = CodeAction.Create(
"Introduce and initialize field '" + parameterName + "'",
ct => CreateFieldAsync(context, parameter, parameterName, parameterName, ct));
context.RegisterRefactoring(action);
}
开发者ID:hakenr,项目名称:RoslynCodeRefactoringPlayground,代码行数:26,代码来源:CodeRefactoringProvider.cs
示例18: 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();
}
}
开发者ID:tategriffin,项目名称:Cartographer,代码行数:32,代码来源:CartographerCodeRefactoringProvider.cs
示例19: 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.AsKeyword))
return;
var node = token.Parent as BinaryExpressionSyntax;
context.RegisterRefactoring(
CodeActionFactory.Create(token.Span, DiagnosticSeverity.Info, GettextCatalog.GetString("Convert 'as' to cast"), t2 => Task.FromResult(PerformAction(document, root, node)))
);
}
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:25,代码来源:ReplaceSafeCastWithDirectCastCodeRefactoringProvider.cs
示例20: 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
注:本文中的Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论