0

Use of DateTime within the roslyn CSharpScript evaluator returns error code 'Expected ;' while strings work fine.

Using Visual Studio 2019 with Microsoft.CodeAnalysis.Common and Microsoft.CodeAnalysis.CSharp.Scripting 3.3.1

Understanding that the evaluator requires configuration, added DateTime assembly along with the custom class assembly.

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);

Cannot understand here why a basic DateTime object causes issues.

String resolves to "i => i.TargetDateTime > 10/25/2019 11:00:00 AM". Wrapping in quotes causes it to be interpreted as string.

EDIT: I should add that hard-coding the string to the example above also fails with same error message, leading me to believe it is a parsing issue? It's not sure how to handle the characters within a DateTime object?

4

1 回答 1

1

问题正如您所说 - 字符串正在解析为"i => i.TargetDateTime > 10/25/2019 11:00:00 AM"无效的 C# 代码。即使添加了引号,也不能直接将 aDateTime与 a进行比较string

最终,您要么需要比较相同类型的对象。to , stringto , to等。我更喜欢将它们保留为对象。stringDateTimeDateTimelonglongDateTime

因此,您需要DateTime在表达式的右侧构造 a 。

一种方法是使用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()})";
于 2019-10-25T18:30:58.123 回答