我正在尝试使用 Roslyn API 做一些基本的代码差异,但遇到了一些意想不到的问题。本质上,我有两段相同的代码,除了添加了一行。这应该只返回已更改文本的行,但由于某种原因,它告诉我一切都已更改。我也尝试过只编辑一行而不是添加一行,但我得到了相同的结果。我希望能够将此应用于源文件的两个版本,以识别两者之间的差异。这是我目前正在使用的代码:
SyntaxTree tree = SyntaxTree.ParseCompilationUnit(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello, World!"");
}
}
}");
var root = (CompilationUnitSyntax)tree.Root;
var compilation = Compilation.Create("HelloWorld")
.AddReferences(
new AssemblyFileReference(
typeof(object).Assembly.Location))
.AddSyntaxTrees(tree);
var model = compilation.GetSemanticModel(tree);
var nameInfo = model.GetSemanticInfo(root.Usings[0].Name);
var systemSymbol = (NamespaceSymbol)nameInfo.Symbol;
SyntaxTree tree2 = SyntaxTree.ParseCompilationUnit(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello, World!"");
Console.WriteLine(""jjfjjf"");
}
}
}");
var root2 = (CompilationUnitSyntax)tree2.Root;
var compilation2 = Compilation.Create("HelloWorld")
.AddReferences(
new AssemblyFileReference(
typeof(object).Assembly.Location))
.AddSyntaxTrees(tree2);
var model2 = compilation2.GetSemanticModel(tree2);
var nameInfo2 = model2.GetSemanticInfo(root2.Usings[0].Name);
var systemSymbol2 = (NamespaceSymbol)nameInfo2.Symbol;
foreach (TextSpan t in tree2.GetChangedSpans(tree))
{
Console.WriteLine(tree2.Text.GetText(t));
}
这是我得到的输出:
System
using System
Collections
Generic
using System
Linq
using System
Text
namespace HelloWorld
{
class Program
{
static
Main
args
{
Console
WriteLine
"Hello, World!"
Console.WriteLine("jjfjjf");
}
}
}
Press any key to continue . . .
有趣的是,它似乎将每一行显示为每一行的标记,除了添加的行,它显示该行而不分解它。有谁知道如何隔离实际的变化?