c# - 使用外部定义类型的 CSharpScript - 无法从类型 A 转换为 A

标签 c# .net-core .net-assembly csharpscript

问题:无法在 CSharpScript 中使用外部定义的类型,因为我猜是由于某些程序集不匹配,它无法将对象类型从自身转换为自身。

我有 2 个项目。

常见

using System;

namespace Common
{
    public class Arguments
    {
        public string Text;
    }

    public class Output
    {
        public bool Success;
    }
}

CSharpScriptingExperiment

using System;
using System.Collections.Generic;
using Common;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;

public class Parameters
{
    public string text;

    public Arguments arguments;
}

namespace CSharpScriptingExperiment
{
    class Program
    {
        static void Main(string[] args)
        {   
            ScriptOptions options = ScriptOptions.Default.WithImports(new List<string>() { "Common" });

            options = options.AddReferences(typeof(Arguments).Assembly);

            // Script will compare the text inside arguments object to the text passed in via function parameters
            var script = CSharpScript.Create(@"
                public class TestClass
                {
                    public Output DoSomething(string text, Arguments args)
                    {
                        return new Output() { Success = args.Text == text };
                    }
                }", options: options, globalsType: typeof(Parameters));

            var nextStep = script.ContinueWith<object>("return new TestClass().DoSomething(text, arguments);");

            // Setup the global paramters object
            Parameters parameters = new Parameters();
            parameters.text = "Hello";
            parameters.arguments = new Arguments()
            {
                Text = "Hello"
            };

            // Run script
            Output output = (Output)nextStep.RunAsync(globals: parameters).Result.ReturnValue;

            Console.WriteLine(output.Success);
            Console.ReadLine();
        }
    }
}

当我运行 CSharpScriptingExperiment 时出现此错误:

"(1,42): error CS1503: Argument 2: cannot convert from 'Common.Arguments [/Users/username/Projects/CSharpScriptingExperiment/CSharpScriptingExperiment/bin/Debug/netcoreapp2.2/Common.dll]' to 'Common.Arguments [Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]'"

在这一行:

Output output = (Output)nextStep.RunAsync(globals: parameters).Result.ReturnValue;

Common 是一个 .NET Standard 2.0 项目。

CSharpScriptingExperiment 是一个 .NET Core 2.2 项目。

有什么想法吗?我见过其他人遇到过类似的问题,但没有找到解决方案。

最佳答案

通过轻微的变通办法让它工作。

当涉及到 CSharpScript 时,有 2 个不同的范围。一个是函数、类等内部代码的正常 C# 范围。第二个是 CSharpScript 的独特功能,即静态范围。它允许变量和代码在不在类或函数中的情况下运行——有点像 REPL。

问题是,当一个外部类型对象被加载到静态作用域中,然后又应该被传递到一个接受该类型参数的函数中时,静态作用域和普通作用域的对象表示是不兼容。这是导致问题的中间静态范围。

所以它是这样的:

Executing Assembly -> Script Static Scope -> Script Normal Scope

这导致了上述问题。

执行此操作时:

Executing Assembly -> Script Normal Scope

Script Normal Scope -> Executing Assembly

一切正常。

因此我可以将外部类型对象从函数返回到正在执行的程序集,但不能通过首先通过静态作用域将外部类型对象传递到函数中。

解决方法是在函数中接受一个对象,然后将该对象转换为函数内部的外部类型。

using System;
using System.Collections.Generic;
using Common;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;

public class Parameters
{
    public string text;

    public Arguments arguments;
}

namespace CSharpScriptingExperiment
{
    class Program
    {
        static void Main(string[] args)
        {   
            ScriptOptions options = ScriptOptions.Default.WithImports(new List<string>() { "Common" });

            options = options.AddReferences(typeof(Arguments).Assembly);

            // Script will compare the text inside arguments object to the text passed in via function parameters
            var script = CSharpScript.Create(@"
                public class TestClass
                {
                    public Output DoSomething(string text, object arguments)
                    {
                        Arguments args = (Arguments)arguments;
                        return new Output() { Success = args.Text == text };
                    }
                }", options: options, globalsType: typeof(Parameters));

            var nextStep = script.ContinueWith<object>("return new TestClass().DoSomething(text, arguments);");

            // Setup the global paramters object
            Parameters parameters = new Parameters();
            parameters.text = "Hello";
            parameters.arguments = new Arguments()
            {
                Text = "Hello"
            };

            // Run script
            Output output = (Output)nextStep.RunAsync(globals: parameters).Result.ReturnValue;

            Console.WriteLine(output.Success);
            Console.ReadLine();
        }
    }
}

所以核心要点是,只要对象不通过静态范围的方式,事情就会按预期进行。如果对象需要通过静态范围,将其作为一个对象处理,并在目标函数内部强制转换为它需要的任何内容——脚本引擎似乎在执行强制转换本身时存在问题,并且类型从根本上是冲突的。

这完全基于黑盒测试和调试 - 我希望 Roslyn 团队能够对此进行权衡,或者让从事内部工作的人来检查我的直觉和发现是否正确。

希望它能帮助其他遇到此问题的人!

关于c# - 使用外部定义类型的 CSharpScript - 无法从类型 A 转换为 A,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55906058/

相关文章:

c# - 在简单的 WCF Rest 服务中查看 JSON 输出

c# - 如何将字节数组(SQL 服务器时间戳)转换为日期时间(C#)?

.net-core - .NET Core 运行时是否向后兼容以前的版本?

.net-core - Stripe 帐单地址 C#/Dotnet 核心

c# - OpCode.Call to Generic Method in different assembly 使用原始 IL

c# - 错误模块名称 : KERNELBASE. dll

c# - 从不同项目的 appsettings.json 中读取多个连接字符串

c# - 将程序集加载到新的 AppDomain 中以进行静态类/方法调用时出现问题

c# - C# 中的访问级别修饰符与程序集加载

c# - 从 IIS 请求中获取原始套接字