Implement with block using temporary variable

This commit is contained in:
GrahamTheCoder 2017-11-27 20:23:50 +00:00
Родитель 92b5f82ab8
Коммит 3ee3be8c62
3 изменённых файлов: 52 добавлений и 3 удалений

Просмотреть файл

@ -16,6 +16,7 @@ namespace RefactoringEssentials.CSharp.Converter
{
SemanticModel semanticModel;
NodesVisitor nodesVisitor;
public const string WithBlockTempVariableName = "withBlock";
public bool IsIterator { get; set; }
@ -255,6 +256,18 @@ namespace RefactoringEssentials.CSharp.Converter
throw new NotSupportedException();
}
public override SyntaxList<StatementSyntax> VisitWithBlock(VBSyntax.WithBlockSyntax node)
{
var withExpression = (ExpressionSyntax) node.WithStatement.Expression.Accept(nodesVisitor);
var variableDeclaratorSyntax = SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(WithBlockTempVariableName), null, SyntaxFactory.EqualsValueClause(withExpression));
var declaration = SyntaxFactory.LocalDeclarationStatement(SyntaxFactory.VariableDeclaration(
SyntaxFactory.IdentifierName("var"),
SyntaxFactory.SingletonSeparatedList(variableDeclaratorSyntax)));
var statements = node.Statements.SelectMany(s => s.Accept(this));
return SingleStatement(SyntaxFactory.Block(new[] {declaration}.Concat(statements).ToArray()));
}
private bool ConvertToSwitch(ExpressionSyntax expr, SyntaxList<VBSyntax.CaseBlockSyntax> caseBlocks, out SwitchStatementSyntax switchStatement)
{
switchStatement = null;

Просмотреть файл

@ -819,10 +819,18 @@ namespace RefactoringEssentials.CSharp.Converter
{
var simpleNameSyntax = (SimpleNameSyntax)node.Name.Accept(this);
var left = (ExpressionSyntax)node.Expression?.Accept(this);
var left = (ExpressionSyntax) node.Expression?.Accept(this);
if (left == null)
return SyntaxFactory.MemberBindingExpression(simpleNameSyntax);
else if (node.Expression.IsKind(VBasic.SyntaxKind.GlobalName))
{
if (!node.Parent.Parent.IsKind(VBasic.SyntaxKind.WithBlock))
{
return SyntaxFactory.MemberBindingExpression(simpleNameSyntax);
}
left = SyntaxFactory.IdentifierName(MethodBodyVisitor.WithBlockTempVariableName);
}
if (node.Expression.IsKind(VBasic.SyntaxKind.GlobalName))
{
return SyntaxFactory.AliasQualifiedName((IdentifierNameSyntax) left, simpleNameSyntax);
}

Просмотреть файл

@ -215,6 +215,34 @@ class TestClass
}");
}
[Fact]
public void WithBlock()
{
TestConversionVisualBasicToCSharp(@"Class TestClass
Private Sub TestMethod()
With New StringBuilder
.Capacity = 20
.Length = 0
End With
End Sub
End Class", @"using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualBasic;
class TestClass
{
private void TestMethod()
{
{
var withBlock = new StringBuilder();
withBlock.Capacity = 20;
withBlock.Length = 0;
}
}
}");
}
[Fact]
public void ArrayInitializationStatement()
{