ConstantExpression 方法
ConstantExpression
必须与 MemberExpression
的类型相同。此示例中的值是一个字符串,在创建 ConstantExpression
实例之前将其转换。
private static ConstantExpression GetConstant(Type type, string value)
{
// Discover the type, convert it, and create ConstantExpression
ConstantExpression constant = null;
if (type == typeof(int))
{
int num;
int.TryParse(value, out num);
constant = Expression.Constant(num);
}
else if(type == typeof(string))
{
constant = Expression.Constant(value);
}
else if (type == typeof(DateTime))
{
DateTime date;
DateTime.TryParse(value, out date);
constant = Expression.Constant(date);
}
else if (type == typeof(bool))
{
bool flag;
if (bool.TryParse(value, out flag))
{
flag = true;
}
constant = Expression.Constant(flag);
}
else if (type == typeof(decimal))
{
decimal number;
decimal.TryParse(value, out number);
constant = Expression.Constant(number);
}
return constant;
}