就我而言,我收到如下错误
Message=(1,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
Source=Microsoft.CodeAnalysis.Scripting
当我调用以下方法时。
private static async Task TrialUsingRoslynScriptingApi1()
{
var scriptOptions = ScriptOptions.Default;
var assemblies = AppDomain.CurrentDomain.GetAssemblies(); // .SingleOrDefault(assembly => assembly.GetName().Name == "MyAssembly");
foreach (Assembly assembly in assemblies)
scriptOptions = scriptOptions.AddReferences(assembly);
scriptOptions = scriptOptions.AddImports("System");
scriptOptions = scriptOptions.AddImports("System.Collections.Generic");
var codeString = @"iList =>
{
var finalResult = 0;
foreach (var i in iList)
finalResult = finalResult + i;
return finalResult;
};
return arithmeticSum;";
Func<List<int>, int> arithmeticSum = await CSharpScript.EvaluateAsync<Func<List<int>, int>>(codeString, scriptOptions);
var iListOfNumbers = new List<int>() { 1, 2, 3, 4, 5 };
Console.WriteLine(arithmeticSum.Invoke(iListOfNumbers));
Console.WriteLine(arithmeticSum(iListOfNumbers));
}
为了缓解这种情况,我将 codeString 更改为以下内容。注意最后的 return 语句和开头的赋值。
var codeString = @"Func<List<int>, int> arithmeticSum = iList =>
{
var finalResult = 0;
foreach (var i in iList)
finalResult = finalResult + i;
return finalResult;
};
return arithmeticSum;";
请注意,这不是一个常规用例,我正在尝试使用 roslyn(.NET Compiler platform) 即时编译一段代码。
要运行此示例,请执行以下操作。
- 在 .net core 上创建一个控制台应用程序
- 添加Microsoft.CodeAnalysis.CSharp.Scripting nuget包。
- 根据需要添加以下部分或全部 using 语句。
使用语句
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
- 最后调用方法如下。
Program.cs 文件中的 main 方法应如下所示。
static async Task Main(string[] args)
{
Console.WriteLine("Hello World! A demo of string to lambda with Roslyn");
await TrialUsingRoslynScriptingApi1();
}