微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 解析“DateTime.Now”?

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

"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!)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐