我需要翻译这样的字符串:
"DateTime.Now.AddDays(-7)"
转化为它们的等价表达式。
我只对 DateTime 类感兴趣。 .Net 中是否有内置的东西可以帮助我做到这一点,或者我只需要编写自己的小解析器?
您可以雇用FLEE http://flee.codeplex.com/为您进行表达式解析。下面的代码经过测试并在 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!)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)