使用字符串值创建 lambda 表达式 ConstantExpression
我想创建 lambda 表达式,提供属性名称、值(作为字符串)和属性类型(作为类型)。
问题在于 Expression.Constant(value1, propertyType);
传递给 Foo 的 value1 是字符串。并且必须解析为“未知”类型
static Expression<Func<T, bool>> LabmdaExpression<T>(string property1, string value1,
Type propertyType)
{
var parameterExpression = Expression.Parameter(typeof(TheObject), "o");
var memberExpression1 = Expression.PropertyOrField(parameterExpression, property1);
//casting?
var valueExpression1 = Expression.Constant(value1, propertyType);
var binaryExpression1 = Expression.GreaterThan(memberExpression1, valueExpression1);
return Expression.Lambda<Func<T, bool>>(binaryExpression1, parameterExpression);
}
I want to create lambda expression providing property name, a value (as string) and property type (as Type).
The problem with that is in line Expression.Constant(value1, propertyType);
value1 that is passed to Foo is string. and must be parsed to "unknown" type
static Expression<Func<T, bool>> LabmdaExpression<T>(string property1, string value1,
Type propertyType)
{
var parameterExpression = Expression.Parameter(typeof(TheObject), "o");
var memberExpression1 = Expression.PropertyOrField(parameterExpression, property1);
//casting?
var valueExpression1 = Expression.Constant(value1, propertyType);
var binaryExpression1 = Expression.GreaterThan(memberExpression1, valueExpression1);
return Expression.Lambda<Func<T, bool>>(binaryExpression1, parameterExpression);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您当前拥有
TheObject
的位置应该拥有T
。要转换字符串,您可以调用
Convert.ChangeType()
方法并转换生成的对象:
仅进行转换是行不通的,因为像
(int)"42"
这样的代码无效。I think you should have
T
where you currently haveTheObject
.To convert the string, you can call the
Convert.ChangeType()
method in your expression and cast the resulting object:Just casting won't work, because code like
(int)"42"
is not valid.