c# - 使用 List 创建脚本

标签 c# scripting

我正在尝试使用 Microsoft.CodeAnalysis.CSharp.Scripting 创建一个脚本.
一旦我添加 List<>代码错误。我以为我已经包含了所有必要的引用资料和用途,但是它仍然出现错误说明 The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?这些是我在代码中的用途

using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics;
下面是我的示例单元测试
[TestMethod]
public void RunGenericListTest()
{
    var code = @"
List<string> strings = new List<string>();
strings.Add(""test string"");            
return output;";

    var options = ScriptOptions.Default;

    options.WithReferences(typeof(System.Collections.CollectionBase).Assembly);
    options.WithReferences(typeof(System.Collections.Generic.List<>).Assembly);
    options.WithImports("System.Collections");
    options.WithImports("System.Collections.Generic");

    var result = CSharpScript.RunAsync(code, options).Result;

    Debug.WriteLine(result);
}
CSharpScript.RunAsync上的这个错误每次。有人可以启发我了解我所缺少的吗?

最佳答案

我认为问题是,WithImports不会改变选项而是改变 returns a copy

var code = @"
List<string> strings = new List<string>();
strings.Add(""test string"");            
return strings;";

    var options = ScriptOptions.Default
                .WithImports("System.Collections.Generic"); // chaining methods would work better here.
    // alternatively reassign the variable:
    // options = options.WithImports("System.Collections.Generic");

    var result = CSharpScript.RunAsync(code, options).Result;

    Debug.WriteLine((result.ReturnValue as List<string>).First());

关于c# - 使用 List 创建脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64927416/

相关文章:

c# - 为什么重写 == 必须重写 equals?

c# - Windows Phone 7、登录屏幕重定向和 .exit 的案例?

c# - 从异步点返回后线程在做什么?

c# - 使用反射返回所有对象属性(包括私有(private)属性)

python-3.x - 获取 Boto3 中具有特定标签和值的 EC2 实例列表

java - 什么是嵌入到 Java 游戏引擎中的良好、简单的脚本语言?

shell - Zsh - 使用点运算符时按空格拆分字符串

c# - 使用 LINQ,您将如何从列表中过滤掉特定条件中除一项以外的所有项?

scripting - 无法使用 TF.exe 确定工作区

linux - 未找到命令 - 脚本编写腻子错误?