在罗斯林DateTime评估器中使用CSharpScript将返回“预期的”错误代码,而字符串可以正常工作。
在Microsoft.CodeAnalysis.Common和Microsoft.CodeAnalysis.CSharp.Scripting 3.3.1中使用VisualStudio2019
了解评估程序需要配置,添加了DateTime程序集和自定义类程序集。
public class Install
{
public int InstallId { get; set; }
public int RegistrationId { get; set; }
public int EnvironmentId { get; set; }
public DateTime SubmitDateTime { get; set; }
public string SubmitIdentity { get; set; }
public DateTime TargetDateTime { get; set; }
public string InstallerIdentity { get; set; }
public DateTime? StartDateTime { get; set; }
public DateTime? StopDateTime { get; set; }
public string Status { get; set; }
}string queryText;
var fooFuture = DateTime.Now.AddDays(7);
var fooPast = DateTime.Now.AddDays(-7);
switch (TimeFrame)
{
case "future": // fails (expected) //
queryText = $"i => i.TargetDateTime < fooFuture";
break;
case "current": // works //
queryText = "i => i.Status == \"In Progress\"";
break;
case "past": // fails with interpolation -- expecting ; //
queryText = $"i => i.TargetDateTime > {fooPast}";
break;
default: // fails with DateTime -- expecting ; //
queryText = $"i => i.TargetDateTime < {DateTime.Now.AddDays(15)} && i.TargetDateTime > {DateTime.Now.AddDays(-15)}";
break;
}
ScriptOptions options = ScriptOptions.Default
.AddReferences(typeof(Install).Assembly)
.AddReferences(typeof(System.DateTime).Assembly);
Func<Install, bool> queryTextExpression = await CSharpScript.EvaluateAsync<Func<Install, bool>>(queryText, options);无法理解为什么一个基本的DateTime对象会导致问题。
字符串解析为"i => i.TargetDateTime > 10/25/2019 11:00:00 AM"。用引号包装使其被解释为字符串。
编辑:我应该补充一下,在上面的例子中,硬编码字符串同样会失败,导致我相信这是一个解析问题?它不确定如何处理DateTime对象中的字符?
发布于 2019-10-25 18:30:58
问题就像您说的--字符串正在解析为"i => i.TargetDateTime > 10/25/2019 11:00:00 AM",这是无效的C#代码。即使添加了引号,也不能直接将DateTime与string进行比较
最终,您需要比较同一类型的对象。string to string,DateTime to DateTime,long to long,等等。我更喜欢把它们保留为DateTime对象。
因此,您需要在表达式的右侧构造一个DateTime。
一种方法是使用DateTime构造函数,如下所示:
queryText = $"i => i.TargetDateTime > new System.DateTime({fooPast.Ticks}, System.DateTimeKind.{fooPast.Kind})";另一种可以说更干净的机制是通过内置的二进制序列化方法,这些方法在单个值中同时考虑了Ticks和Kind:
queryText = $"i => i.TargetDateTime > System.DateTime.FromBinary({fooPast.ToBinary()})";https://stackoverflow.com/questions/58563643
复制相似问题