Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using Microsoft.CSharp;
- using System.CodeDom.Compiler;
- class Program
- {
- static void Main(string[] args)
- {
- var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
- var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
- parameters.GenerateExecutable = true;
- CompilerResults results = csc.CompileAssemblyFromSource(parameters,
- @"using System.Linq;
- class Program {
- public static void Main(string[] args) {
- var q = from i in Enumerable.Range(1,100)
- where i % 2 == 0
- select i;
- }
- }");
- results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
- }
- }
- public abstract class BaseClass
- {
- public virtual void Foo1() { }
- public virtual bool Foo2() { return false; }
- ...
- }
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using Microsoft.CodeAnalysis;
- using Microsoft.CodeAnalysis.CSharp;
- using Microsoft.CodeAnalysis.Emit;
- namespace RoslynCompileSample
- {
- class Program
- {
- static void Main(string[] args)
- {
- SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
- using System;
- namespace RoslynCompileSample
- {
- public class Writer
- {
- public void Write(string message)
- {
- Console.WriteLine(message);
- }
- }
- }");
- string assemblyName = Path.GetRandomFileName();
- MetadataReference[] references = new MetadataReference[]
- {
- MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
- MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location)
- };
- CSharpCompilation compilation = CSharpCompilation.Create(
- assemblyName,
- syntaxTrees: new[] { syntaxTree },
- references: references,
- options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
- using (var ms = new MemoryStream())
- {
- EmitResult result = compilation.Emit(ms);
- if (!result.Success)
- {
- IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
- diagnostic.IsWarningAsError ||
- diagnostic.Severity == DiagnosticSeverity.Error);
- foreach (Diagnostic diagnostic in failures)
- {
- Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
- }
- }
- else
- {
- ms.Seek(0, SeekOrigin.Begin);
- Assembly assembly = Assembly.Load(ms.ToArray());
- Type type = assembly.GetType("RoslynCompileSample.Writer");
- object obj = Activator.CreateInstance(type);
- type.InvokeMember("Write",
- BindingFlags.Default | BindingFlags.InvokeMethod,
- null,
- obj,
- new object[] { "Hello World" });
- }
- }
- Console.ReadLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement