Advertisement
BurningBunny

Microsoft Roslyn Example

Feb 12th, 2014
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.82 KB | None | 0 0
  1. using Roslyn.Compilers;
  2. using Roslyn.Compilers.CSharp;
  3.  
  4. [...]
  5.  
  6. var text = @"class Calc { public static object Eval() { return 42; } }";
  7.  
  8. var tree = SyntaxTree.ParseCompilationUnit(text);
  9. var compilation = Compilation.Create(
  10.     "calc.dll",
  11.     options: new CompilationOptions(assemblyKind: AssemblyKind.DynamicallyLinkedLibrary),
  12.     syntaxTrees: new[] { tree },
  13.     references: new[] { new AssemblyFileReference(typeof(object).Assembly.Location) });
  14.  
  15. Assembly compiledAssembly;
  16. using (var stream = new MemoryStream())
  17. {
  18.     EmitResult compileResult = compilation.Emit(stream);
  19.     compiledAssembly = Assembly.Load(stream.GetBuffer());
  20. }
  21.  
  22. Type calc = compiledAssembly.GetType("Calc");
  23. MethodInfo eval = calc.GetMethod("Eval");
  24. string answer = eval.Invoke(null, null).ToString();
  25.  
  26. Assert.AreEqual("42", answer);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement