C# 解析;DateTime.Now;?

C# 解析;DateTime.Now;?,c#,string,parsing,datetime,C#,String,Parsing,Datetime,我需要像这样翻译字符串: "DateTime.Now.AddDays(-7)" 转化为它们的等价表达式 我只对DateTime课程感兴趣。Net中是否有任何东西可以帮助我完成这项工作,或者我只需要编写自己的小解析器?您可以使用它来为您进行表达式解析。下面的代码是在Silverlight中测试和工作的(我相信完整的C#,它在创建表达式时可能有稍微不同的语法,但无论如何它可能完全像这样工作) 为什么需要解析代码?我不明白这个要求?他们的“等价表达”是什么?我不知道这是什么意思。你可以使用类似的方法

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

"DateTime.Now.AddDays(-7)"
转化为它们的等价表达式

我只对DateTime课程感兴趣。Net中是否有任何东西可以帮助我完成这项工作,或者我只需要编写自己的小解析器?

您可以使用它来为您进行表达式解析。下面的代码是在Silverlight中测试和工作的(我相信完整的C#,它在创建表达式时可能有稍微不同的语法,但无论如何它可能完全像这样工作)


为什么需要解析代码?我不明白这个要求?他们的“等价表达”是什么?我不知道这是什么意思。你可以使用类似的方法来为你做表达式解析。逃离是否适用于DateTime?新闻。从他们的网站:“任何类型的变量都可以在表达式中动态定义和使用”--“DateTime-一个有效的.NET DateTime模式,由#包围。使用ExpressionOptions.DateTimeFormat属性来控制格式。例如:#08/06/2008#。ToLongDateString()”嗨,Chris,这正是我需要的。什么是ExpressionFactory,这是一种逃逸型吗?我看不到(我有版本0.9.26.0)。@PaulHennessey,可能是Silverlight特有的;我使用一个特殊的兼容版本。如果你看一下他们的例子,他们使用了一种稍微不同的机制(
context.CompileDynamic
context.CompileGeneric
)就是这样!谢谢Chris,它与context.CompileGeneric一起工作。明亮的
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!)