最近有一个工作希望能够在WPF嵌入一个C#编译器,所以我打算使用由微软提供的Rosyln。
版本选择
当前的Rosyln版本为:
- 稳定版version-1.3.2
- 最新版version-2.0.0-beta5
我的WPF工程的框架采用.Net Framework 4.5,采用的是最新版(2.0.0-beta5)。在采用稳定版(1.3.2)时,程序在编译或者运行时会出现如下错误:
未能加载文件或程序集“System.Runtime, Version=4.0.20.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”或它的某一个依赖项。
这主要是由于在当前框架下,程序集的版本和Rosyln所需版本不符导致的。出错的程序集不止System.Runtime,还有包括System.Threading,System.Collections等其他程序集都会出现这样的错误。如果由于某些原因必须要用1.3.2版本,则可以参考《使用roslyn代替MSBuild完成解决方案编译》。
安装
利用Visual Studio自带的Nuget包管理器安装以下包(勾选“包括预发行版”)
- Microsoft.CodeAnalysis.Common (version-2.0.0-beta5)
- Microsoft.CodeAnalysis.CSharp (version-2.0.0-beta5)
管理器会自动安装相关的依赖项,等待安装完成即可。
一个小Demo
在安装好后,写了一个小Demo尝试了一下,就是实现了最简单的编译C#的代码功能
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
//在合适的位置放下这个函数
public void Compile()
{
string text = textBox.Text;
SyntaxTree tree = CSharpSyntaxTree.ParseText(text);
List<MetadataReference> references = new List<MetadataReference>()
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
};
var root = ((CompilationUnitSyntax)tree.GetRoot());
CSharpCompilationOptions options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
CSharpCompilation compilation = CSharpCompilation.Create("GraphDrawer", new[] { tree }, references, options);
using (MemoryStream stream = new MemoryStream())
{
var result = compilation.Emit(stream);
if (!result.Success)
{
foreach (var r in result.Diagnostics)
{
//r可能是错误(error)也可能是警告(warning)
//r.Id; 错误消息的代码
//r.GetMessage();错误信息
//r.Severity.ToString();error还是warning
//var lineSpan = r.Location.GetLineSpan();
//lineSpan.StartLinePosition.Line+1;错误位置行
//lineSpan.StartLinePosition.Character;错误位置列
}
}
}
}