Using System.Dynamic in Roslyn

后端 未结 5 1852
死守一世寂寞
死守一世寂寞 2020-12-05 03:28

I modified the example that comes with the new version of Roslyn that was released yesterday to use dynamic and ExpandoObject but I am getting a compiler error which I am no

相关标签:
5条回答
  • 2020-12-05 04:06

    If your project is targeting .Net Core or .Net Standard, then instead of adding reference you can install the Microsoft.CSharp NuGet package to solve this error.

    0 讨论(0)
  • 2020-12-05 04:09

    To make the code work in .Net Core 2.1 I had to add this references in the compilation:

    var compilation = CSharpCompilation.Create(
        "calc.dll",
        options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
        syntaxTrees: new[] {tree},
        references: new[] {
            MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
            MetadataReference.CreateFromFile(typeof(ExpandoObject).Assembly.Location),
            MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.CSharp")).Location),
            MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("netstandard")).Location),
            MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("mscorlib")).Location),
            MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Runtime")).Location),            
        }
    );
    
    0 讨论(0)
  • 2020-12-05 04:11

    ASP.NET MVC specific:

    You can get this error in an MVC 6 controller if you forget to put [FromBody] in a POST method.

        [HttpPost("[action]")]
        public void RunReport([FromBody]dynamic report)
        {
            ...
        }
    

    The .NETCore default project already includes Microsoft.CSharp reference but you get pretty much the same message.

    With [FromBody] added you can now post JSON and then just dynamically access the properties :-)

    0 讨论(0)
  • 2020-12-05 04:13

    You may also want to check the properties of all your project references. Make sure any reference is using .NET newer than 2.0. I have a project that was referencing another project in the same solution and had to rebuild the dependency using a newer .NET framework target.

    See this post.

    Also, don't forget to add the Microsoft.CSharp reference to you main project like @Alberto said.

    0 讨论(0)
  • 2020-12-05 04:24

    I think that you should reference the Microsoft.CSharp.dll assembly

    0 讨论(0)
提交回复
热议问题