c# - 解析 "DateTime.Now"?

标签 c# string parsing datetime

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

"DateTime.Now.AddDays(-7)"

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

我只对 DateTime 类感兴趣。 .Net 中是否有任何内置功能可以帮助我执行此操作,还是我只需要编写自己的小解析器?

最佳答案

您可以雇用 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!)

关于c# - 解析 "DateTime.Now"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14647703/

相关文章:

c# - ASP.NET 缓存是如何工作的?

jquery - jquery attr 的字符串操作,对我不起作用

Python:Scrapy 蜘蛛不返回结果?

iphone - 更新annotationView中的字幕

c# - 如何将带小数点的字符串解析为 double ?

带有标签特定信息的 Python XML 解析

c# - System.Configuration 的线程安全使用

c# - Web 应用程序错误 : Sequence contains more than one element

c# - 如何在没有对话框的情况下打印 XPS?

c - C 中的字符串操作和系统调用