我想将Expression<Func<Loan, bool>>
转换为字符串,反之亦然。我可以做吗?如何实现ConvertStringToExpression
方法?
internal class Program
{
public class Loan
{
public bool IsActive { get; set; }
}
private static void Main(string[] args)
{
Expression<Func<Loan, bool>> expression = l => !l.IsActive;
var expStr = ConvertExpressionToString(expression);
var exp = ConvertStringToExpression(expStr);
}
public static string ConvertExpressionToString(Expression<Func<Loan, bool>> expression)
{
//return ???
throw new NotImplementedException();
}
public static string ConvertStringToExpression(string expression)
{
//return ???
throw new NotImplementedException();
}
}
答案 0 :(得分:0)
很久以前,您可以使用ScottGu的blog中详述的DynamicLinq库。这个库有一个类ExpressionParser
,它包含解析框架的所有组件来解析字符串表达式并将它们转换回Expression
。
以下是其中一种用法:
public static Expression Parse(Type resultType, string expression, params object[] values)
{
ExpressionParser parser = new ExpressionParser(null, expression, values);
return parser.Parse(resultType);
}