使用列表创建脚本

Creating a script with List

我正在尝试使用 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());