在使用最新版本的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
关键字时,我通常会遇到一些随机的编译错误,例如以下之一:
error CS1001: 需要标识符
error CS1003: 语法错误,需要 ','
error 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论坛也没有答案。PS: 据我所知,
async
关键字是为了增加人类和编译器的可读性,而await
则完成所有的魔法。