简体   繁体   English

解析“DateTime.Now”?

[英]Parsing “DateTime.Now”?

I need to translate strings like this: 我需要翻译这样的字符串:

"DateTime.Now.AddDays(-7)"

into their equivalent expressions. 到他们的等效表达式。

I'm only interested in the DateTime class. 我只对DateTime类感兴趣。 Is there anything built into .Net that'll help me do this, or do I just need to write my own little parser? .Net中有什么内容可以帮助我做到这一点,还是我只需要编写自己的小解析器?

You can employ FLEE to do the expression parsing for you. 您可以使用FLEE为您执行表达式解析。 The below code is tested and working in Silverlight (I believe in full C#, it may have a slightly different syntax around creating the expression, but it might work exactly like this anyway) 下面的代码在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!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM