在CSharpScript中传递数组作为输入参数报错的问题求助
问题分析与解决方法
问题重现
自定义方法代码:
public class TaskSolution { public int[] Calculate(int[] inputValue) { return inputValue; } }
调用代码:
var script = CSharpScript.Create(solution.Code); var input = new int[3] { 1, 2, 3 }; var call = await script.ContinueWith<int[]>($"new TaskSolution().Calculate({input})").RunAsync();
运行时抛出Microsoft.CodeAnalysis.Scripting.CompilationErrorException,错误信息:(1,43): error CS0443: Syntax error; value expected
原因
字符串插值时,{input}会调用数组的ToString()方法,输出结果是System.Int32[],这不是合法的C#数组初始化语法,导致脚本编译失败。
解决方法
方法一:将数组转换为合法的C#数组语法字符串
手动把数组序列化为脚本能识别的数组初始化代码:
var script = CSharpScript.Create(solution.Code); var input = new int[3] { 1, 2, 3 }; // 生成类似"new int[] { 1, 2, 3 }"的字符串 var inputExpr = $"new int[] {{ {string.Join(", ", input)} }}"; var call = await script.ContinueWith<int[]>($"new TaskSolution().Calculate({inputExpr})").RunAsync();
方法二:使用脚本参数传递(推荐)
通过脚本的globals参数直接传递数组对象,避免字符串拼接的语法问题:
var script = CSharpScript.Create(solution.Code); var input = new int[3] { 1, 2, 3 }; // 脚本中直接引用参数名input var call = await script.ContinueWith<int[]>("new TaskSolution().Calculate(input)", globals: new { input }).RunAsync();
如果需要更复杂的参数场景,也可以通过ScriptOptions配置:
var options = ScriptOptions.Default.WithImports("System"); var script = CSharpScript.Create(solution.Code, options); var input = new int[3] { 1, 2, 3 }; var call = await script.ContinueWith<int[]>("new TaskSolution().Calculate(input)", new { input }).RunAsync();
内容的提问来源于stack exchange,提问作者Sterlukin
相关产品推荐
相关产品推荐

