c# - Roslyn c# CSharpCompilation - 编译动态

标签 c# .net dynamic roslyn

Roslyn 编译器和动力学 --> 我正在尝试编译仅在运行时已知的属性。
在 Visual Studio 中编译时代码有效。使用 Roslyn 编译时,动态属性为“未知”。

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

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

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

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。您的“硬编码”示例试图将 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);
}

关于c# - Roslyn c# CSharpCompilation - 编译动态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58453115/

相关文章:

url - 在运行时创建 XmlRpcUrl 接口(interface)

c# - Entity Framework - 填充子对象,过滤子对象

c# - "BeginSession"方法未被调用或未成功 - QBFC SDK12 和 ASP.NET 网站

c# - FromArgb 与 FromScRgb

c# - 在这种情况下捕获异常的最佳做法是什么

javascript - 编写新文本时更改文本框文本的颜色

c# - 如何使 x 轴忽略 x 值的顺序?

asp.net - 无法评估表达式

c - 如何在获取输入的同时在数字数组中创建实时动态内存分配?

jquery - 右对齐表格中的数值和 <thead>