gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:57:30 28 4
gpt4 key购买 nike

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com