简体   繁体   English

当语句应该为真时,Roslyn CSharpScript EvaluateAsync 返回 False

[英]Roslyn CSharpScript EvaluateAsync Returns False When Statement Should Be True

I am just learning how to use Roslyn and I have a script like this:我只是在学习如何使用 Roslyn,我有一个这样的脚本:

var id = Guid.NewGuid();
string condition = $@"new List<Guid> {{ new Guid(""{Guid.NewGuid()}""), new Guid(""{id}"") }}.Any(id => id == new Guid(""{id}""));";

var result = CSharpScript.EvaluateAsync<bool>(condition, 
             Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
             .WithImports("System", "System.Collections.Generic", "System.Linq")
             .AddReferences(typeof(System.Linq.Enumerable).Assembly)).Result;

result is coming back as false.结果返回为假。 I even tried:我什至尝试过:

var id = Guid.NewGuid();
string condition = $@"new List<Guid> {{ new Guid(""{Guid.NewGuid()}""), new Guid(""{id}"") }}.Any(id => true);";

It also results in false.它也会导致错误。 I debugged it and grabbed the value in condition and after taking the escaping characters out, it is:我对其进行了调试并在条件中获取了值,在取出 escaping 字符后,它是:

var result = new List<Guid> { new Guid("907eb45d-8646-4b1b-baed-54d451f9753a"),
               new Guid("fef76d20-0066-4ee5-901e-2936c2117a8a") }.Any(id => true);

Which results in true.结果是真的。 I'm not sure where I'm going wrong with this.我不确定我哪里出了问题。

Not sure why, but the removing the semi-colon at the end of the statement allowed it to return true.不知道为什么,但是在语句末尾删除分号允许它返回 true。

string condition = $@"new List<Guid> {{ new Guid(""{Guid.NewGuid()}""), new Guid(""{id}"") }}.Any(id => id == new Guid(""{id}""))";

instead of:代替:

string condition = $@"new List<Guid> {{ new Guid(""{Guid.NewGuid()}""), new Guid(""{id}"") }}.Any(id => id == new Guid(""{id}""));";

EvaluateAsync is an async function. EvaluateAsync是一个异步 function。 It will not return data immediately.它不会立即返回数据。 You will need to put the await keyword before it to wait for the computation.您需要将await关键字放在它之前等待计算。

If you don't, the result variable will init with default value false when you check it before the EvaluateAsync return.如果不这样做,当您在EvaluateAsync返回之前检查结果变量时, result变量将初始化为默认值false

var result = await CSharpScript.EvaluateAsync<bool>(condition, 
             Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
             .WithImports("System", "System.Collections.Generic", "System.Linq")
             .AddReferences(typeof(System.Linq.Enumerable).Assembly)).Result;

You can read more about Asynchronous programming here: https://docs.microsoft.com/en-us/dotnet/csharp/async您可以在此处阅读有关异步编程的更多信息: https://docs.microsoft.com/en-us/dotnet/csharp/async

Because you didn't get a return value.因为你没有得到返回值。 the code should be as follows.代码应如下所示。

string condition = $@"return new List<Guid> {{ new Guid(""{Guid.NewGuid()}""), new Guid(""{id}"") }}.Any(id => id == new Guid(""{id}""));";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM