解析" DateTime.Now"? [英] Parsing "DateTime.Now"?
本文介绍了解析" DateTime.Now"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要这样的翻译字符串:
I need to translate strings like this:
"DateTime.Now.AddDays(-7)"
到他们的等值表达式。
into their equivalent expressions.
我只DateTime类感兴趣。有什么内置的.Net那会帮助我做到这一点,或者我只需要编写自己的小解析器?
I'm only interested in the DateTime class. Is there anything built into .Net that'll help me do this, or do I just need to write my own little parser?
推荐答案
您可以使用 FLEE 做表达式分析为您服务。下面的代码进行测试,并在Silverlight中工作(我相信完整的C#,它可能围绕创建表达式的语法稍有不同,但也可能正是这样的工作反正)
You can employ FLEE to do the expression parsing for you. 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)
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!)
这篇关于解析" DateTime.Now"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文