我正在嘗試用Roslyn重寫代碼。 我想將GreaterThanToken更改爲EqualsEqualsToken。這是我到目前爲止的代碼:羅斯林代碼重寫
//ToParse.cs
public class ToParse
{
public bool MethodToConvert(int param)
{
return (1 > param);
}
}
//Program.cs
class Rewriter : SyntaxRewriter
{
private readonly SyntaxKind _replace;
private readonly SyntaxKind _replacewith;
public Rewriter(SyntaxKind replace, SyntaxKind replacewith)
{
_replace = replace;
_replacewith = replacewith;
}
public override SyntaxToken VisitToken(SyntaxToken token)
{
if (token.Kind != _replace)
{
return token;
}
return Syntax.Token(_replacewith);
}
}
var code = new StreamReader("ToParse.cs").ReadToEnd();
var tree = SyntaxTree.ParseText(code);
var root = tree.GetRoot();
var rewriter = new Rewriter(SyntaxKind.GreaterThanToken, SyntaxKind.EqualsEqualsToken);
var newRoot = rewriter.Visit(root);
var newTree = SyntaxTree.Create((CompilationUnitSyntax)newRoot);
var compilation = Compilation.Create("TestAssembly.dll",
new CompilationOptions(OutputKind.DynamicallyLinkedLibrary),
references: new[]{ new MetadataFileReference(typeof(object).Assembly.Location)},
syntaxTrees: new[] { newTree });
Console.WriteLine(newTree);
EmitResult res;
using (var file = new FileStream("e:\\TestAssembly.dll", FileMode.Create))
{
res = compilation.Emit(file);
}
執行後,Console.WriteLine打印改變令牌return (1 == param);
但是當我打開testassembly.dll與ilspy我仍然看到return 1 > param;
有什麼建議?
你重建項目? – jgauffin
是的,我也試過調試/發佈配置 – mrK
Roslyn不允許你在編譯過程中重寫。 – SLaks