【问题标题】:Parsing "DateTime.Now"?解析“DateTime.Now”?
【发布时间】:2013-02-01 13:47:17
【问题描述】:

我需要像这样翻译字符串:

"DateTime.Now.AddDays(-7)"

转换成它们的等价表达式。

我只对 DateTime 类感兴趣。 .Net 中是否有任何内置功能可以帮助我做到这一点,还是我只需要编写自己的小解析器?

【问题讨论】:

  • 为什么需要解析代码?我不明白要求?
  • “他们的等价表达”是什么?我不知道那是什么意思。
  • 你可以使用FLEE之类的东西来为你做表达式解析。
  • 是否可以使用 DateTime?给我的消息。
  • 来自他们的网站:“任何类型的变量都可以动态定义并在表达式中使用”--“DateTime - 由 # 包围的有效 .NET DateTime 模式。使用 ExpressionOptions.DateTimeFormat 属性控制格式。例如:#08/06/2008#.ToLongDateString()"

标签: c# string parsing datetime


【解决方案1】:

您可以使用FLEE 为您进行表达式解析。下面的代码在 Silverlight 中经过测试和工作(我相信在完整的 C# 中,创建表达式的语法可能略有不同,但无论如何它可能完全像这样工作)

ExpressionContext context = new ExpressionContext();

//Tell FLEE to expect a DateTime result; if the expression evaluates otherwise, 
//throws an ExpressionCompileException when compiling the expression
context.Options.ResultType = typeof(DateTime);

//Instruct FLEE to expose the `DateTime` static members and have 
//them accessible via "DateTime".
//This mimics the same exact C# syntax to access `DateTime.Now`
context.Imports.AddType(typeof(DateTime), "DateTime");

//Parse the expression, naturally the string would come from your data source
IDynamicExpression expression = ExpressionFactory.CreateDynamic("DateTime.Now.AddDays(-7)", context);

//I believe there's a syntax in full C# that lets you evaluate this 
//with a generic flag, but in this build, I only have it return type 
//`Object` so we cast (it does return a `DateTime` though)
DateTime date = (DateTime)expression.Evaluate();

Console.WriteLine(date); //January 25th (7 days ago for me!)

【讨论】:

  • 嗨,克里斯,看起来正是我需要的。什么是 ExpressionFactory,是 FLEE 类型吗?我看不到它(我有 FLEE 版本 0.9.26.0)。
  • @PaulHennessey 这可能是 Silverlight 特定的;我使用一个特殊的兼容版本。如果您查看他们的 Getting Started 示例,他们使用的机制略有不同(context.CompileDynamic 或 context.CompileGeneric)
  • 就是这样!谢谢 Chris,它适用于 context.CompileGeneric。太棒了!
猜你喜欢
  • 1970-01-01
  • 2017-01-09
  • 2022-12-05
  • 1970-01-01
  • 2010-09-19
  • 2010-09-08
  • 2020-02-23
  • 1970-01-01
  • 2011-01-09
相关资源
最近更新 更多