将字符串转换为Func
本文关键字:Object Func 字符串 转换 | 更新日期: 2023-09-27 18:14:04
我有以下方法
public List<ServicesLogModel> Paging(Func<ServicesLogModel, bool> condition, string columnOrder, bool? orderDescending, int? pageIndex, int? pageSize, out int total)
{
return _mongoRepository.Paging(condition, order => order.Message, orderDescending.Value, pageIndex.Value, pageSize.Value, out total);
}
columnOrder
参数是一个字符串作为lambda表达式(例如:order => order.Message
),我必须将其转换为Func<T, object>
我正在尝试使用Expression.Parameter
var parm = Expression.Parameter(typeof(ServicesLogModel), "order");
var propName = Expression.Property(parm, columnOrder);
Expression predicateBody = Expression.Assign(parm, propName);
var test=Expression.Lambda<Func<ServicesLogModel, object>>(predicateBody, parm);
它不起作用错误:不能使用"System"类型的表达式。为类型"ServicesLogModel"赋值的字符串
编辑:方法签名
public List<T> Paging(Func<T, bool> condition, Func<T, object> order, bool orderDescending, int pageIndex, int pageSize,out int total)
调用方法
[HttpGet]
[Route("Admin/GetReaderConnectorLog/{Apikey}/{SecretKey}/{index}/{pagesize}/{orderAsc}/{columnOrder}")]
public IActionResult GetReaderConnectorLog(string Apikey, string SecretKey, int? index, int? pagesize, bool? orderAsc, string columnOrder)
{
try
{
_userService.BeginTransaction();
// _webApiHelper.ValidateApiKey(Apikey, SecretKey, Context, _userService, true);
int total;
//TEST
var listModel = _connectorLogService.Paging(_ => true, $"order => order.{columnOrder}", orderAsc, index, pagesize, out total);
_userService.Commit();
return _webApiHelper.OkResponse($"{_appSettings.Options.UserTag}[Send List User]", Context, new PaginationModel<ServicesLogModel> { ListData = listModel, Total = total, Apikey = Apikey, SecretKey = SecretKey });
}
catch (Exception e)
{
_userService.Rollback();
return _webApiHelper.ResolveException(Context, e);
}
}
对
最终的解决方案是这样的
public Func<T, object> GetLambda<T>(string property)
{
var param = Expression.Parameter(typeof(T), "p");
Expression parent = Expression.Property(param, property);
if (!parent.Type.IsValueType)
{
return Expression.Lambda<Func<T, object>>(parent, param).Compile();
}
var convert = Expression.Convert(parent, typeof(object));
return Expression.Lambda<Func<T, object>>(convert, param).Compile();
}
由于您的方法需要Func<T,object>
而不是Expression<Func<T,object>>
,一个简单的解决方案是使用反射:
public Func<T, object> GetPropertyFunc<T>(string property_name)
{
return t => typeof (T).GetProperty(property_name).GetMethod.Invoke(t, new object[] {});
}
此方法接受属性的名称,并返回所需的函数。
下面是测试方法:
ServicesLogModel model = new ServicesLogModel()
{
Message = "my message"
};
Func<ServicesLogModel, object> func = GetPropertyFunc < ServicesLogModel>("Message"); //I am assuming the property name is "Message", but you can pass any string here
var message = func(model) as string;