同时使用最新版本的 roslyn-ctp我发现它在编译和脚本执行时不支持 dynamic
关键字,即你会得到一个编译错误 error CS8000: This language feature ('dynamic') is not yet implemented in Roslyn .
这是一个简短的代码片段:
var engine = new ScriptEngine();
var script = @"dynamic someVariable = 0;";
// you an error CS8000: This language feature ('dynamic') is not yet implemented in Roslyn
engine.CreateSession().Execute(script);
在使用 await
关键字时......
相比之下,在编译或脚本中使用 await
关键字时,我通常会遇到一些随机编译错误,例如以下之一:
错误 CS1001:需要标识符
错误 CS1003:语法错误,预期为“,”
错误 CS0246:找不到类型或命名空间名称“await”(是否缺少 using 指令或程序集引用?)
脚本示例
var engine = new ScriptEngine();
new[]
{
"System", "System.Threading", "System.Threading.Tasks",
} .ToList().ForEach(@namespace => engine.ImportNamespace(@namespace));
var script = @"await Task.Run(() => System.Console.WriteLine(""Universal [async] answer is '42'""));";
engine.CreateSession().Execute(script);
编译示例
// compilation sample
const string codeSnippet = @"namespace DemoNamespace
{
using System;
using System.Threading;
using System.Threading.Tasks;
public class Printer
{
public async void Answer()
{
var answer = 42;
var task = Task.Run(() => System.Console.WriteLine(string.Format(""Universal [async] answer is '{0}'"", answer)));
await task; // not working
task.Wait(); // working as expected
}
}
}";
var syntaxTree = SyntaxTree.ParseText(codeSnippet,
options: new ParseOptions(languageVersion: LanguageVersion.CSharp5));
var references = new []
{
MetadataReference.CreateAssemblyReference(typeof(Console).Assembly.FullName),
MetadataReference.CreateAssemblyReference(typeof(System.Threading.Tasks.Task).Assembly.FullName),
};
var compilation = Compilation.Create(
outputName: "Demo",
options: new CompilationOptions(OutputKind.DynamicallyLinkedLibrary),
syntaxTrees: new[] { syntaxTree },
references: references);
if(compilation.GetDiagnostics().Any())
{
compilation.GetDiagnostics().Select(diagnostic => diagnostic).Dump();
throw new Exception("Compilation failed");
}
Assembly compiledAssembly;
using (var stream = new MemoryStream())
{
EmitResult compileResult = compilation.Emit(stream);
compiledAssembly = Assembly.Load(stream.GetBuffer());
}
dynamic instance = Activator.CreateInstance(compiledAssembly.GetTypes().First());
instance.Answer();
问:我是不是遗漏了什么或者它还没有实现?
我尝试过使用 LanguageVersion.CSharp5
和不使用的不同配置。谷歌和 Stackoverflow 搜索都充满了对 roslyn 的营销炒作。和 async关键字,几乎没用。 Microsoft "Roslyn" CTP forum对此也没有答案。
ps:据我所知,async
关键字引入了人类和编译器的可读性,而 await
完成了所有魔法
最佳答案
await
支持未在当前 Roslyn CTP 中实现(尽管它现在已在内部构建中实现)。
错误报告不同的原因是我们首先构建了 Roslyn 解析器,以便它可以处理整个 C# 4 语言,然后一次为一个特性填充语义。由于 await
是 C# 5 的一个特性,它甚至不能被解析器识别,也没有地方可以识别它的使用并提供一个好的错误。
关于c# - Roslyn 可以编译 await 关键字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15312892/