与Roslyn一起编译

时间:2013-08-15 11:42:15

标签: c# compiler-construction roslyn

我正在尝试编译解决方案,但在尝试保存时收到一条晦涩的错误消息。

  

匿名类型<> __ blahblah未完成

然而,在编译的源代码中,没有任何匿名类型。

代码是

private static void Compile(ISolution solution)
    {
        var workspaceServices = (IHaveWorkspaceServices)solution;
        var projectDependencyService = workspaceServices.WorkspaceServices.GetService<IProjectDependencyService>();

        foreach (var projectId in projectDependencyService.GetDependencyGraph(solution).GetTopologicallySortedProjects())
        {
            var currentDomain = AppDomain.CurrentDomain;
            var assemblyName = new AssemblyName();
            assemblyName.Name = "Most." + solution.GetProject(projectId).AssemblyName;

            var assemblyBuilder = currentDomain.DefineDynamicAssembly
                           (assemblyName, AssemblyBuilderAccess.RunAndSave);

            var moduleBuilder = assemblyBuilder.
                                            DefineDynamicModule(assemblyName.Name);
            var types = moduleBuilder.GetTypes();
            types.Aggregate((ts, t) =>
            {
                var tb = t as TypeBuilder;
                return tb.CreateType();
            });
            solution.GetProject(projectId).GetCompilation().Emit(moduleBuilder);
            assemblyBuilder.Save(assemblyName.Name);
        }
    }

1 个答案:

答案 0 :(得分:1)

这是Roslyn的一个错误。它转载于:

var assemblyName = new AssemblyName { Name = "Test" };

var compilation = Compilation.Create(
    assemblyName.Name, new CompilationOptions(OutputKind.DynamicallyLinkedLibrary),
    new[] {
        SyntaxTree.ParseText(@"
using System;
using System.Linq;    

public class C1
{
    public void M1() 
    {
        new[] {1}.Select(_ => new {});
    }
}")
    },
    new[] {
        MetadataReference.CreateAssemblyReference("mscorlib"),
        MetadataReference.CreateAssemblyReference("System.Core")
    });

var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(
    assemblyName, AssemblyBuilderAccess.RunAndSave);
var moduleBuilder = assembly.DefineDynamicModule(assemblyName.Name, assemblyName.Name + ".dll");

var emitResult = compilation.Emit(moduleBuilder);

if (emitResult.Success)
{
    assembly.Save(assemblyName.Name + ".dll"); //Error! Type '<>f__AnonymousType0' was not completed.
}
else
{
    throw new NotImplementedException();
}