假设我们有如下字符串:
string s1 = "a < 5";
string s2 = "b >= 7";
string s3 = "c <= 8";
...
我想将这样的字符串转换为 BinaryExpression 对象,类似于我们通过使用得到的对象:
BinaryExpression b1 = Expression.MakeBinary( ExpressionType.LessThan, Expression.Parameter( typeof( int ), "a" ), Expression.Constant( 5, typeof( int ) ) );
BinaryExpression b2 = Expression.MakeBinary( ExpressionType.GreaterThanOrEqual, Expression.Parameter( typeof( int ), "b" ), Expression.Constant( 7, typeof( int ) ) );
BinaryExpression b3 = Expression.MakeBinary( ExpressionType.LessThanOrEqual, Expression.Parameter( typeof( int ), "c" ), Expression.Constant( 8, typeof( int ) ) );
我创建了以下方法:
BinaryExpression ConvertStringToBinaryExpression( string exp )
{
string[] s = exp.Split( ' ' );
string param = s[ 0 ];
string comparison = s[ 1 ];
int constant = int.Parse( s[ 2 ] );
if ( comparison == "<" )
return Expression.MakeBinary( ExpressionType.LessThan, Expression.Parameter( typeof ( int ), param ), Expression.Constant( constant, typeof ( int ) ) );
else if ( comparison == "<=" )
return Expression.MakeBinary( ExpressionType.LessThanOrEqual, Expression.Parameter( typeof ( int ), param ), Expression.Constant( constant, typeof ( int ) ) );
else if ( comparison == ">" )
return Expression.MakeBinary( ExpressionType.GreaterThan, Expression.Parameter( typeof ( int ), param ), Expression.Constant( constant, typeof ( int ) ) );
else if ( comparison == ">=" )
return Expression.MakeBinary( ExpressionType.GreaterThanOrEqual, Expression.Parameter( typeof ( int ), param ), Expression.Constant( constant, typeof ( int ) ) );
else
throw new ArgumentException( "Invalid expression.", "exp" );
}
但是,例如,如果我们有如下字符串,则上述方法无法正常工作:
string s4 = "a< 5" // no space between 'a' and '<'
string s5 = "b>=9" // no space at all
string s6 = "c <=7" // no space betwen '<=' and '7'
使它更健壮和可靠的最简单方法是什么?