Roslyn c# CSharpCompilation - 编译动态

Roslyn c# CSharpCompilation - Compiling Dynamic

Roslyn 编译器和动力学 --> 我正在尝试编译 属性 仅在运行时已知。
该代码在 Visual studio 中编译时有效。使用 Roslyn 编译时,动态属性为 'unknown'。

在这个示例单元测试中,我有一个继承自 DynamicObject 的 MyObject。这些属性提供了一个简单的键值字典。

当以硬编码方式使用 'MyObject' 时,我可以调用 属性 你好。我实际上可以在编译时使用任何 属性。不存在的属性会在运行时出错。 (预期行为)

在传递给 roslyn 编译器的代码中使用 'MyObject' 时,我无法在我的动态对象上使用任何 属性。这里 属性 'Hello' 给我错误:

CS1061 - 'MyObject' does not contain a definition for 'Hello' and no accessible extension method 'Hello' accepting a first argument of type 'MyObject' could be found (are you missing a using directive or an assembly reference?)

我错过了什么?

示例单元测试:

using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CSharp.RuntimeBinder;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Testing {
    [TestClass]
    public class FullExampleTest {
        [TestMethod]
        public void HardCoded() {
            var map = new Dictionary<string, string>() {
                { "Hello","Foo"},
                { "World","Bar"}
            };
            dynamic src = new MyObject(map);
            Console.WriteLine(src.Hello);

            Assert.AreEqual("Foo Bar", $"{src.Hello} {src.World}");
        }

        [TestMethod]
        public void CompileAtRuntime() {
            string code = @"
                using System;
                using System.Collections.Generic;
                using System.Diagnostics.Contracts;
                using System.Dynamic;
                using System.IO;
                using System.Linq;
                using System.Reflection;
                using Testing;

                namespace MyNamespace{{
                    public class MyClass{{
                        public static void MyMethod(MyObject src){{
                            Console.WriteLine(src.Hello);
                        }}
                    }}
                }}
           ";

            var ns = Assembly.Load("netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51");

            MetadataReference[] references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(ns.Location), //netstandard
                MetadataReference.CreateFromFile(typeof(Object).Assembly.Location), //mscorlib
                MetadataReference.CreateFromFile(typeof(DynamicObject).Assembly.Location), //System.Core
                MetadataReference.CreateFromFile(typeof(RuntimeBinderException).Assembly.Location),//Microsoft.CSharp
                MetadataReference.CreateFromFile(typeof(Action).Assembly.Location), //System.Runtime
                MetadataReference.CreateFromFile(typeof(FullExampleTest).Assembly.Location) // this assembly
            };


            var comp = CSharpCompilation.Create(
                assemblyName: Path.GetRandomFileName(),
                syntaxTrees: new[] { CSharpSyntaxTree.ParseText(code) },
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
            );

            using (var ms = new MemoryStream()) {
                var result = comp.Emit(ms);
                if (!result.Success) {
                    var failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error);

                    foreach (Diagnostic diagnostic in failures) {
                        Console.WriteLine($"{diagnostic.Id} - {diagnostic.GetMessage()}");
                    }
                }
                Assert.IsTrue(result.Success, "Compilation failure..");
            }
        }
    }

    public class MyObject : DynamicObject {
        private IDictionary<string, string> _Map;

        public MyObject(IDictionary<string, string> map) {
            _Map = map;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result) {
            Contract.Assert(binder != null);

            var ret = _Map.TryGetValue(binder.Name, out string value);
            result = value;
            return ret;
        }

        public override bool TryInvokeMember(InvokeMemberBinder binder,     object[] args, out object result) {
            Contract.Assert(binder != null);

            var ret = _Map.TryGetValue(binder.Name, out string value);
            result = value;
            return ret;
        }

    }
}

您的动态编译代码与静态编译代码不同。在您的动态编译代码中,您已将 src 显式声明为 dynamic。您的 "hard-coded" 示例试图将 is 视为 MyObject。如果您的硬编码测试如下所示,您会遇到同样的问题:

    var src = new MyObject(map);
    Console.WriteLine(src.Hello);

因此,您可以通过将 src 转换为 dynamic:

来解决此问题
public static void MyMethod(MyObject src){
    Console.WriteLine(((dynamic)src).Hello);
}

或者首先将其声明为动态的:

public static void MyMethod(dynamic src){
    Console.WriteLine(src.Hello);
}