Roslyn 是以 API 为驱动的下一代编译器,集成在最新版的 Visual Studio 上。它开放 C# 和 Visual Basic 编译器的 API,使得开发者可以借助编译器进行解析代码文件、动态为编程语言增加功能、扩展编译器、自定义编译器动作等操作。
将Roslyn编译结果保存在流中,用程序集加载方法将流加载到当前程序集中,就可以在当前的程序集中调用了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace RoslynDemo
{
class Program
{
static void Main(string[] args)
{
// 加载C#程序集
var assembly = Assembly.Load("System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
var compilation = CSharpCompilation.Create("HelloWorld")
.AddReferences(assembly)
.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree("using System; class Program { static void Main() { Console.WriteLine(\"Hello, World!\"); } }"));
// 生成程序集和语法树
var assembly = compilation.Emit("HelloWorld.dll");
var syntaxTree = compilation.SyntaxTrees.Single();
// 解析语法树并提取方法信息
var root = syntaxTree.GetRoot();
var methods = root.DescendantNodes().OfType<MethodDeclarationSyntax>();
foreach (var method in methods)
{
Console.WriteLine("方法名称:{0}", method.Identifier);
Console.WriteLine("方法返回类型:{0}", method.Type);
Console.WriteLine("方法体:");
Console.WriteLine(method.Body);
Console.WriteLine();
}
}
}
}