我正在尝试使用 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/