gpt4 book ai didi

c# - 将字符串转换为 Func

转载 作者:太空宇宙 更新时间:2023-11-03 21:18:13 27 4
gpt4 key购买 nike

我有以下方法

     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.String”的表达式来分配类型为“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();
}

关于c# - 将字符串转换为 Func<T,Object>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32722731/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com