Roslyn dynamic class generation issue

◇◆丶佛笑我妖孽 提交于 2020-12-13 04:05:50

问题


So I am trying to create a dynamic type (at runtime) using Roslyn. The entire back story to this requirement is too long to go into. I do however need to create a new type which has x many properties, where I am trying to feed in the property names and initial values from a Dictionary

Here is the relevant code

private void CreateAssembly(Dictionary<string, string> propertiesToEmit)
{
    if (ourAssembly == null)
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendLine("using System;");
        sb.AppendLine("public class MyClass");
        sb.AppendLine("{");
        sb.AppendLine("  public static void Main()");
        sb.AppendLine("  {");
        sb.AppendLine("  }");
        foreach (var kvp in propertiesToEmit)
        {
            sb.AppendLine($"  public {kvp.Value} {kvp.Key}" + " { get; set; }");
        }
        sb.AppendLine("  public  MyClass CreateFromDynamic(Dictionary<string, object> sourceItem)");
        sb.AppendLine("  {");
        sb.AppendLine("     MyClass newOne = new MyClass();");
        foreach (var kvp in propertiesToEmit)
        {
            sb.AppendLine($@"  newOne.{kvp.Key} = sourceItem[""{kvp.Key}""];");
        }
        sb.AppendLine("  return newOne;");
        sb.AppendLine("  }");
        sb.AppendLine("}");

        var tree = CSharpSyntaxTree.ParseText(sb.ToString());
        var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
        var dictsLib = MetadataReference.CreateFromFile(typeof(Dictionary<,>).Assembly.Location);

        var compilation = CSharpCompilation.Create("MyCompilation",
            syntaxTrees: new[] { tree }, references: new[] { mscorlib, dictsLib });

        //Emit to stream
        var ms = new MemoryStream();
        var emitResult = compilation.Emit(ms);

        //Load into currently running assembly. Normally we'd probably
        //want to do this in an AppDomain
        ourAssembly = Assembly.Load(ms.ToArray());
    }
}

I get this weird error with Roslyn where it can't seem to find a reference to Dictionary<,> even though this is inside mscorlib which is referenced.

It can clearly be seen that Dictionary<,> does live in a dll (namely mscorlib) that is referenced.

Any ideas?


回答1:


Ok I found the answer, I forgot to add this using statement in code I was creating out using Roslyn

sb.AppendLine("using System.Collections.Generic;");


来源:https://stackoverflow.com/questions/48381483/roslyn-dynamic-class-generation-issue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!